[Tutor] Create file and input text

Cédric Lucantis omer at no-log.org
Sun Jun 29 21:35:00 CEST 2008


Le Sunday 29 June 2008 21:18:31 Dave Kuhlman, vous avez écrit :
> On Sat, Jun 28, 2008 at 08:11:03PM -0400, David wrote:
> > Hi, I am very new to python and it is my first attempt at programing
> > except for some basic bash scripts. I came up with this;
> > #!/usr/bin/python
> >
> > import os
> > filename = raw_input('Enter the filename: ')
> > fobj = open(filename, 'w')
> > yourname = raw_input('What is your name: ')
> > fobj.write(yourname)
> > fobj.close()
> >
> > It seems to work Ok, I was shocked! Is it OK?
>
> It looks like good code to me.  But, one suggestion: It's dangerous
> code, unless you can trust your users.  They can over-write files.  In
> a real application, you might want to do some checking on the file
> before opening it.  Consider using something like this:
>
>     if os.path.exists(filename):
>         print 'Warning.  File %s exists.' % filename
>     else:
>         fobj = open( ...
>

If you really care about overwriting files, there is a race condition here 
(the file could be created between os.path.exists and the open call), so you 
should rather write it like this:

try: fd = os.open(filename, os.O_WRONLY | os.O_EXCL | os.O_CREAT)
except IOError, exc:
	if exc.errno != errno.EEXIST : raise
	print 'File %s already exists.' % filename
fobj = os.fdopen(fd)

(but I guess this doesn't work on all platforms)

-- 
Cédric Lucantis


More information about the Tutor mailing list