[Tutor] reading complex data types from text file
Michiel Overtoom
motoom at xs4all.nl
Wed Jul 15 23:14:36 CEST 2009
Chris Castillo wrote:
> I don't know how to iterate through all the lines and just get the
> integers and store them or iterate through the lines and just get the
> names and store them.
You could use the int() function to try to convert a line to an integer,
and if that fails with a ValueError exception, assume that it is a name.
names=[]
numbers=[]
for line in open("mixed.txt"):
try:
nr=int(line)
# it's an integer
numbers.append(line)
except ValueError:
# it's not an integer
names.append(line)
f=open("numbers.txt","wt")
f.write("".join(numbers))
f.close()
f=open("names.txt","wt")
f.write("".join(names))
f.close()
--
"The ability of the OSS process to collect and harness
the collective IQ of thousands of individuals across
the Internet is simply amazing." - Vinod Valloppillil
http://www.catb.org/~esr/halloween/halloween4.html
More information about the Tutor
mailing list