[Tutor] Create file and input text

David david at abbottdavid.com
Sun Jun 29 22:32:23 CEST 2008


Cédric Lucantis wrote:
>
> Well, you're asking the user to enter -1 after the raw_input, so if the file 
> exists your script will just print 'File exists... -1 to quit' and open it 
> anyway. See my previous post for a better way of handling it, but in your 
> case you should at least do something like this:
>
> filename = raw_input('Enter the filename: ')
> if os.path.exists(filename):
> 	r = raw_input('Warning, file %s exists, overwrite it [y/n] ? ' % filename)
> 	if r != 'y' : sys.exit(0)
> fobj = open(...)
>
>   
Thanks Cédric Lucantis,
I will have to study some more;
os.open(filename, os.O_WRONLY | os.O_EXCL | os.O_CREAT)
Is over my head at this time.

With your suggestion I did come up with this;

#!/usr/bin/python

import os
import sys
filename = raw_input('Enter the filename: ')
if os.path.exists(filename):
    r = raw_input(
'Warning, file %s exists, overwrite it [y/n] ? ' % filename)
if r != 'y' : sys.exit(0)
fobj = open(filename, 'w')
yourname = raw_input('What is your name: ')
fobj.write(yourname)
fobj.close()

-david

-- 
Powered by Gentoo GNU/LINUX
http://www.linuxcrazy.com



More information about the Tutor mailing list