[Tutor] editTextFile.py

Kent Johnson kent37 at tds.net
Thu Sep 13 13:01:07 CEST 2007


Christopher Spears wrote:
> I created a script that opens an existing text file,
> allows the user to write over the original contents,
> and then save the file.  The original contents are
> then saved in a separate file.  Here is the script:
> 
> #!/usr/bin/python
> 
> 'editTextFile.py -- write over contents of existing
> text file'
> 
> import os, string
> 
> # get filename
> while True:
>     fname = raw_input('Enter file name: ')
>     if not (os.path.exists(fname)):
>         print"*** ERROR: '%s' doesn't exist" % fname
>     else:
>         break
> 
> # get file content (text) lines
> all = []
> print "\nEnter lines ('.' by itself to quit).\n"
> 
> # loop until user terminates input
> while True:
>     entry = raw_input('> ')
>     if entry == '.':
>         break
>     else:
>         all.append(entry)
> 
> # write lines to file with NEWLINE line terminator
> print "1) Replace file's contents"
> print "Any other key quits function without replacing
> file's contents"
> choice = raw_input("Make a choice: ")
> 
> if choice == '1':
>     fobj = open(fname, 'r')
>     fobj_lines = fobj.readlines()
>     fobj.close()
>     fobj = open(fname, 'w')

It would be safer to write the '_orig' file before opening the original 
file for writing (which erases its contents)
>     
>     fname_orig = fname + '_orig'
>     fobj_orig = open(fname_orig, 'w')
>     stripped_lines = []
>     for line in fobj_lines:
>     	string.strip(line)

This doesn't change line. You need to assign the result back to line:
   line = string.strip(line)
or, better,
   line = line.strip()

Note that this will also strip leading and trailing whitespace from the 
lines so the copy will not be a duplicate of the original.

A simpler way to copy a file is to read the entire contents using 
fobj.read() and write them as a single string. Even easier is to use 
shutil.copyfile() which does this for you.

Kent


More information about the Tutor mailing list