How to make sure a file exists or can be created before it is written in Python?

I am writing a function and I want it to be a touchfile so that I can write to this file. If the file does not exist, I will get an error. How can I say that?

+3
source share
3 answers

Just open the file for writing and it will be created if it does not exist (if you have the correct permission to write to this place).

f = open('some_file_that_might_not_exist.txt', 'w')
f.write(data)

You will receive IOErrorif you cannot open the file for writing.

+12
source

Per docs, os.utime () will work similar to touching if you give it None as a time argument, for example:

os.utime("test_file", None)

( Linux Windows), , test_file . YMMV .

, . , try.. , .

+7

if you really want to raise an error if the file does not exist, you can use

import os
if not os.access('file'):
    #raise error
f = open('file')
#etc.
0
source

Source: https://habr.com/ru/post/1769222/


All Articles