[Tutor] Create file and input text

Cédric Lucantis omer at no-log.org
Sun Jun 29 22:53:12 CEST 2008


Le Sunday 29 June 2008 22:32:23 David, vous avez écrit :
> 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

Sounds good to me, it should be enough for your needs. Just remember that the 
file could be created by another process between the calls to 
os.path.exists() and open(), which is a real security problem in a 'serious' 
application. Read this if you want to know more (this is the libc 
documentation, but the os python module uses the same syntax and flags) :

http://www.gnu.org/software/libc/manual/html_node/Opening-and-Closing-Files.html#Opening-and-Closing-Files
http://www.gnu.org/software/libc/manual/html_node/Open_002dtime-Flags.html#Open_002dtime-Flags

-- 
Cédric Lucantis


More information about the Tutor mailing list