[Tutor] creating files and writing to them
Michael P. Reilly
arcege@shore.net
Thu, 3 Jun 1999 10:40:15 -0400 (EDT)
> 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] )
Just for a little, more portable, change (on UNIX): the expanduser()
function in the os.path module resolves "~username" from the
/etc/passwd file.
if len(sys.argv) > 1:
username = sys.argv[1]
homedir = os.path.expanduser('~' + username)
doc_filename = os.path.join(homedir, 'docname')
doc_file = open(doc_filename, 'w')
startupfile = open(username + '.startup', 'w')
...
Not all systems/users may have their home directories in "/home/".
-Arcege