[Tutor] file I/O

ak@silmarill.org ak@silmarill.org
Wed, 11 Jul 2001 16:45:32 -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")
> 	done = 0
> 	while not done:
> 		aLine = infile.readline()
> 		if aLine != " ":
                if aLine:           # clearer, and works :-)
> 			f.write(aLine + '\n')
> 		else:
> 			done = 1

I usually do something like:

while 1:
    l = infile.readline()
    if not l: break
    f.write(l)

I think it's more straightforward and clear..  The reason people feel
the need for 'done' variables and such is that in this idiom you have to create
an infinite loop and then break out of it - that's two things that just don't
feel right. break feels like something you'd do in case of an error.. afaik,
this will be fixed in 2.2 that will provide a clean and clear idiom, and until
then, the above idiom is the right choice, because everybody who feels uneasy
about it first always gets over it and uses it, like I did. Everybody comes
to realize it's lesser of two evils :-P.

> 	infile.close()
> 	f.write("\n\nEOF\n")
I'm not sure this is needed, but I never used Mac.
> 	f.close()
Files will be closed anyway when program ends, by the way.
> 
> if __name__ == '__main__':
> 	finout()
> 
> 
> 
> 
> Get 250 color business cards for FREE!
> http://businesscards.lycos.com/vp/fastpath/
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor

-- 
Cymbaline: intelligent learning mp3 player - python, linux, console.
get it at: http://silmarill.org/cymbaline