[Tutor] Strings and file saving

Moshe Zadka Moshe Zadka <moshez@math.huji.ac.il>
Sat, 19 Aug 2000 12:31:02 +0300 (IDT)


On Fri, 18 Aug 2000, Daniel D. Laskey, CPA wrote:

> import sys
> import string
> 
> # get the appropriate data file
> in_file = open("data_file","r")
> 
> # create the file to export the data to
> out_file = open("junk2.txt","w+")
> 
> # read each line in the file	
> for line in in_file.readlines():
> 	if string.find(line,'$')>= 0:
> #		# "print line" works well

Instead of:

> #		#print line
> 		a = line
> #	# write the new file you created to the file "junk2.txt"
> 	out_file.write(a)

Why not just:

>		out_file.write(line)

(Your problem was that you tried to call out_file.write(a) before you
ever assigned to a: your first line had no '$'. Be thankful, for
otherwise you'd have a nasty bug: a line with a '$' would be printed
from when it was read until the next one was read, once for every line.

IOW, the output for:

1$
2
3$

Would be

1$
1$
3$

Instead of

1$
3$
--
Moshe Zadka <moshez@math.huji.ac.il>
There is no IGLU cabal.
http://advogato.org/person/moshez