[Tutor] file I/O

D-Man dsh8290@rit.edu
Wed, 11 Jul 2001 16:50:04 -0400


On Thu, Jul 12, 2001 at 04:56:49AM +0900, kevin parks wrote:
| Hi. I am a little confused as to why this hangs when i run it. I am
| trying to make a script that opens a file for input opens a file for
| writing and reads in a line from the input and copies it to the
| created output file. In this case except for  the start here and EOF
| lines the file should be an exact copy. (the point is that later i an
| going to do something to each line of text), but i have to get this
| much working, plus the other business i mentioned on UNIX and Mac
| paths, but first this, Why does it just hang the interpreter? 
| 
| This is in Mac OS 9.bloat Python 2.1 IDE
| 
| 
| def finout():
| 
| 	infilename = raw_input('Enter in file name: ')
| 	infile = open(infilename, 'r')
| 	f = open('sys:scripts:foo.txt', 'w')
| 	f.write("start here\n\n")

As Arcege said, the loop's terminating condition is incorrect.

| 	done = 0
| 	while not done:
| 		aLine = infile.readline()
| 		if aLine != " ":
| 			f.write(aLine + '\n')
| 		else:
| 			done = 1

I would recommend the following instead :

while 1 :
    aLine = infile.readline()
    if not aLine : break

    f.write(aLine)

It is more compact, and it is the standard idiom for reading a file
line-by-line.

However, if you are using a new enough version of Python (2.1 I think,
maybe 2.0) you can use the following instead :

for aLine in infile.xreadlines() :
    f.write( aLine )

| 	infile.close()
| 	f.write("\n\nEOF\n")
| 	f.close()
| 
| if __name__ == '__main__':
| 	finout()


HTH,
-D