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

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

$
0
0

It doesn't seem like there's a meaningful functional difference between try/except and isfile(), so you should use which one makes sense.

If you want to read a file, if it exists, do

try:    f = open(filepath)except IOError:    print 'Oh dear.'

But if you just wanted to rename a file if it exists, and therefore don't need to open it, do

if os.path.isfile(filepath):    os.rename(filepath, filepath +'.old')

If you want to write to a file, if it doesn't exist, do

# python 2if not os.path.isfile(filepath):    f = open(filepath, 'w')# python 3, x opens for exclusive creation, failing if the file already existstry:    f = open(filepath, 'wx')except IOError:    print 'file already exists'

If you need file locking, that's a different matter.


Viewing all articles
Browse latest Browse all 47

Latest Images

Trending Articles



Latest Images

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