标签云

微信群

扫码加入我们

WeChat QR Code


Actual duplicate question: Safely create a file if and only if it does not exist with python. In Python 3.3+, use the 'x' flag when open()ing a file to avoid race conditions.

2018年10月23日56分28秒

Of course, you can get into a race condition where the file doesn't exist when you check, but springs into existence before you can create it. Extremely unlikely, but possible.

2018年10月23日56分28秒

This will return true if a directory exists by the given name, in which case a subsequent creation of the file will fail.

2018年10月23日56分28秒

I think you are thinking of os.path.exists, which returns True if the path exists (i.e. is a file or a directory). As shown above, os.path.isfile returns True when the path is a regular file.

2018年10月23日56分28秒

For Python 3 need to replace file with open: if not os.path.exists(filename): open(filename, "w+").close()

2018年10月23日56分28秒

Did you mean to say, "The latter will create the file if it does not exist."?

2018年10月23日56分28秒

Note that file(filename, 'w+').close() will truncate file if it exists.

2018年10月23日56分28秒

This does work, but fobj = os.fdopen(fd) should be fobj = os.fdopen(ds, 'w') and after that os.close(fd).

2018年10月23日56分28秒

Opps, scratch os.close(fd)

2018年10月23日56分28秒

Actually the line needs to be fobj = os.fdopen(fd, 'w'). That's 'fd' not 'ds'

2018年10月23日56分28秒

That exception catches everything and handles it all the same... it would be better if you explicitly named what should be getting caught there.

2018年10月23日56分28秒

open() is not an ideal solution compared to os.isfile. Open does unnecessary actions if you just want to check the existence of the file (though it is true, open is the best way to read and write files), and requires read privileges of the file to verify the existence of the file.

2018年10月23日56分28秒