[Tutor] Equivalent exception of os.path.exists()

bibi midi bibsmendez at gmail.com
Tue Dec 1 06:46:40 CET 2009


Thanks to all of you that replied. Your inputs are very helpful and
informative.


On Tue, Dec 1, 2009 at 12:14 AM, Sander Sweers <sander.sweers at gmail.com>wrote:

>
> There is no exception to alert you a file already exists. Depending on
> how you open the file (mode) it will either read, write or append to
> the file. If the file exists and you open it in write mode it *will*
> overwrite the file. See [1] for more info.
>
> So what you need to do is check yourself if the file exists and make
> the python script take appriate action. For example:
>
> import os
> fname = "C:\\testfile.txt"
> if os.path.exists(fname):
>    do something if exists
> else:
>   do something else if not exists
>
> Greets
> Sander
>

Like i thought so, there is no exception to catch if a file already exist.
I've been browsing the many types of exceptions and cant find anything thats
close. Thank you for clarifying.

I may have misunderstood the exercise question and will have to return to it
to do another approach.

For the record below is the working copy of the script. Here i understand
how the os.path.exists() method works.

while True:
    fname = raw_input('please enter filename: ')
    if os.path.exists(fname):
        print('ERROR: %s exists!') % fname
    elif fname.isspace():
        print('Space is not allowed!')
    else:
        print('you entered %s') % fname
        break

all = []        # container list to hold user input lines
print "\nPopulate your file! \n"
quit_prompt = "[to quit enter a dot '.' by itself]--> "

while True:
    entry = raw_input(quit_prompt)
    if entry == '.':
        break
    else:
        all.append(entry)

confirm = raw_input('save file to disk?(y/N)')
confirm = confirm.lower()   #convert to lowercase
if confirm == 'y':
    fobj = open(fname, 'w')
    fobj.write('\n'.join(all))
    fobj.close()
    print('DONE! open %s to view your file') % fname
else:
    print 'not saving to disk!'
    sys.exit()

Thank you.


-- 
Best Regards,
bibimidi
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20091201/edbf57be/attachment-0001.htm>


More information about the Tutor mailing list