Folks,

I want to know how to check whether a file exists for not??

One more thing: If we open an existing file in a write mode, then it gets truncated to zero length, so what the way out of this??
Should I use open('filename','w+')

Regards,
Asrar

Use:

os.path.exists(filename)  # returns True or False

I you don't want to truncate an existing file with 'w' or 'w+' use the 'a' option for append.

Folks,

I want to know how to check whether a file exists for not??

One more thing: If we open an existing file in a write mode, then it gets truncated to zero length, so what the way out of this??
Should I use open('filename','w+')

Regards,
Asrar

You can also go with this way.

try:
    open('filepath','mode')
except IOError, err:
    print 'IOError: ',err

IOError, exception will arise when there is no file exists in the specified path.


[One more thing: If we open an existing file in a write mode, then it gets truncated to zero length, so what the way out of this??
Should I use open('filename','w+')]

for this you can try opening a file in append mode, that is

open('filepath','a')

when close the opened file(Eg:'filepath') its orginal content will be there unless modify the file.

cheers.
kath.

This question has already been answered. Start a new discussion instead.