Home  >  Q&A  >  body text

In python, the problem about using format to open the document

Use the format method to open the image, but I don’t know what this code means. See the screenshot?

with open ("map{n:02d}.png".format(n=0), "wb") as f:  # format 02d 两位整数
    f.write(data)

ringa_leeringa_lee2669 days ago997

reply all(2)I'll reply

  • 仅有的幸福

    仅有的幸福2017-06-28 09:27:15

    The

    with statement is a context management method for opening and closing files. For example, the general opening posture is

    file = open("filename", 'wb')
    # do something
    file.close()

    With context management, withAfter the code block is executed, the internal method will be called to directly close the file. There is no need to manually call the close() method, which is the way given in the question.
    Of course format is a method of formatting strings. The position of {n} is reserved in the string. n will be used as the key of a keyword parameter. After the value is passed in, the passed in will be used. valuereplacement, so the position of {n:02d} in the question will be replaced by the integer string received by n. If only {} is left in the string, and no key value is specified, then the parameter passed in format will be used as a positional parameter, and will be filled in order one by one corresponding to the {} in the string.

    reply
    0
  • 漂亮男人

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

    Format string

    Equivalent to: "map" + "00" + ".png"

    reply
    0
  • Cancelreply