[Tutor] Create file and input text

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


Le Sunday 29 June 2008 21:53:17 David, vous avez écrit :
> Dave Kuhlman wrote:
> > 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( ...
> >
> >
> > - Dave
>
> Thanks Dave, cool name :)
> here is what I came up with, seems to work as expected;
> #!/usr/bin/python
>
> import os
> filename = raw_input('Enter the filename: ')
> if os.path.exists(filename):
>     print 'Warning.  File %s exists. -1 to quit' % filename
> if (filename != -1):
>     fobj = open(filename, 'w')
> yourname = raw_input('What is your name: ')
> fobj.write(yourname)
> fobj.close()

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(...)

-- 
Cédric Lucantis


More information about the Tutor mailing list