Heim  >  Fragen und Antworten  >  Hauptteil

In Python besteht das Problem bei der Verwendung des Formats zum Öffnen des Dokuments

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)

ringa_leeringa_lee2669 Tage vor994

Antworte allen(2)Ich werde antworten

  • 仅有的幸福

    仅有的幸福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将作为位置参数,按顺序一一与字符串中的{}对应进行填补。

    Antwort
    0
  • 漂亮男人

    漂亮男人2017-06-28 09:27:15

    格式化字符串

    等价于:"map" + "00" + ".png"

    Antwort
    0
  • StornierenAntwort