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

Recommended Answers

All 2 Replies

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.