[Tutor] editTextFile.py

Christopher Spears cspears2002 at yahoo.com
Thu Sep 13 05:36:01 CEST 2007


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')
    
    fname_orig = fname + '_orig'
    fobj_orig = open(fname_orig, 'w')
    stripped_lines = []
    for line in fobj_lines:
    	string.strip(line)
	stripped_lines.append(line)
    fobj_orig.write('\n'.join(stripped_lines))
    fobj_orig.close()
    
    fobj.write('\n'.join(all))
    fobj.close()
    print 'DONE!'
else:
    print 'Bye!'

I took a file called myfile.  The original contents of
myfile were:
Hi!
This is my file.
It really rocks!

I then ran my script:
Enter file name: myfile

Enter lines ('.' by itself to quit).

> test
> test
> test
> .
1) Replace file's contents
Any other key quits function without replacing file's
contents
Make a choice: 1
DONE!

Now the contents of myfile are:
test
test
test

The original contents were saved in myfile_orig.  The
contents of myfile_orig are:
Hi!

This is my file.

It really rocks!

Extra newlines were added.  This won't do.  I think
the problem lies with 

fobj_orig.write('\n'.join(stripped_lines))

However, when I rewrite this line code as

fobj_orig.write(string.join(stripped_lines))

I get 

Hi!
 This is my file.
 It really rocks!

That doesn't work either.  Any suggestions?


More information about the Tutor mailing list