Quantcast
Channel: How do I check whether a file exists without exceptions? - Stack Overflow
Viewing all articles
Browse latest Browse all 46

Answer by bergercookie for How do I check whether a file exists without exceptions?

$
0
0

If the file is for opening you could use one of the following techniques:

with open('somefile', 'xt') as f: #Using the x-flag, Python3.3 and above    f.write('Hello\n')if not os.path.exists('somefile'):     with open('somefile', 'wt') as f:        f.write("Hello\n")else:    print('File already exists!')

UPDATE

Just to avoid confusion and based on the answers I got, current answer finds either a file or a directory with the given name.


Viewing all articles
Browse latest Browse all 46

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>