[Tutor] creating files and writing to them

Ivan Van Laningham ivanlan@callware.com
Thu, 03 Jun 1999 07:57:54 -0600


Hi Todd etc.--

Todd Martin wrote:
> 
> Ok so I can do these things in perl and shell but I'm just now learning
> python and am a little confused.
> 
> What I want to do is pass a username to a script as an argument like so:
> 
> % script username
> 
> Then write a file named "username.startup".
> 
> This is where I'm at right now:
> 
> #! /usr/bin/python
> 
> file = open('/home/todd/docname', 'w')
> file.write('The create script in its infancy\n')
> file.close()
> 
> def docname ():
>         username = "todd"
>         startup = ".startup"
>         doc = username + startup
>         print "%s" % doc
> 
> docname()
> 
> I know its lame so far but I'm new :)
> 
> Ok so that last tidbit there is how I figured I could take the username and
> append ".startup" to it. But now I need to create a file by that name, rather
> than the way its being done now, where I have to declare the file name in
> advance (does that make sense?).
> 
> Now I know I will need to pass the username argument to argv, but that can wait untill I find out how to pass file = open() a variable rather than a file name.
> 
> Is this clear? I'm not entirely sure I know how to word this right.
> 
> Any help would be very appreciated!
> 

#!/usr/bin/python
# I see that you're on RedHat Linux;-)
if len ( sys.argv ) > 1 :
  homedir = "/home/"
  username = sys.argv[1]
  startup = "/.startup"

  startupfile = open ( homedir + username + startup, 'w' )
  file.write('The create script in its infancy\n')
  file.close()
else :
  print "Usage:  %s username" % ( sys.argv[0] )

<ask-us-something-hard>-ly y'rs,
Ivan
----------------------------------------------
Ivan Van Laningham
Callware Technologies, Inc.
ivanlan@callware.com
http://www.pauahtun.org
See also: 
http://www.foretec.com/python/workshops/1998-11/proceedings.html
Army Signal Corps:  Cu Chi, Class of '70
----------------------------------------------