What does python3 open “x” mode do?

前端 未结 3 1588
情深已故
情深已故 2021-01-01 09:51

What does the new open file mode \"x\" do in python 3?

here is the doc of python 3:

\'r\': open for reading (default)

\'w\': open

3条回答
  •  南笙
    南笙 (楼主)
    2021-01-01 10:40

    As @Martjin has already said, you have already answered your own question. I would only be amplifying on the explanation in the manual so as to get a better understanding of the text

    'x': open for exclusive creation, failing if the file already exists

    When you specify exclusive creation, it clearly means, you would use this mode for exclusively creating the file. The need for this is required when you won't accidentally truncate/append an existing file with either of the modes w or a.

    In absence of this, developers should be cautious to check for the existence of the file before leaping to open the file for updation.

    With this mode, your code would be simply be written as

    try:
        with open("fname", "x") as fout:
            #Work with your open file
    except FileExistsError:
        # Your error handling goes here
    

    Previously though your code might had been written as

    import os.path
    if os.path.isfile(fname):
        # Your error handling goes here
    else:
        with open("fname", "w") as fout:
            # Work with your open file
    

提交回复
热议问题