Heim > Fragen und Antworten > Hauptteil
Verwenden Sie die Formatierungsmethode, um das Bild zu öffnen, aber ich weiß nicht, was dieser Code bedeutet. Sehen Sie sich den Screenshot an?
with open ("map{n:02d}.png".format(n=0), "wb") as f: # format 02d 两位整数
f.write(data)
仅有的幸福2017-06-28 09:27:15
with
语句是文件打开和关闭的上下文管理写法,比如一般的打开姿势是
file = open("filename", 'wb')
# do something
file.close()
而使用上下文管理,with
代码块执行结束后,会调用内部的方法直接关闭文件,不需要再手动调用close()
方法,就是问题中给出的写法。
当然format
就是字符串个格式化的一个方法,字符串内留作{n}
的位置,n
会作为一个关键字参数的key,传入值后,会使用传入value
替换,于是题目中的{n:02d}
的位置会被替换为n
接收的整数字符串。如果字符串内仅仅留为{}
,其中并没有指定key值,那么参数传入format
将作为位置参数,按顺序一一与字符串中的{}
对应进行填补。