[Tutor] Create file and input text

Dave Kuhlman dkuhlman at rexx.com
Sun Jun 29 21:18:31 CEST 2008

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
        fobj = open( ...

- Dave

Dave Kuhlman

More information about the Tutor mailing list