[Tutor] handling a textfile
Alan Gauld
alan.gauld at btinternet.com
Wed Aug 19 11:54:56 CEST 2009
"Olli Virta" <llvirta at gmail.com> wrote
> I have a textfile (job.txt) that needs modifying. The structure of this
> file
> is like this:
>
> AAA1...
> BBB1...
> CCC1...
> AAA2...
> BBB2...
> CCC2...
> etc...
> Question is how can I turn this all to a textfile (done.txt) that is
> suppose
> to look like this:
>
> AAA1...BBB1...CCC1...
> AAA2...BBB2...CCC2...
Lots of ways to do it. The simplest is to read the variables line by line,
so, in pseudo code:
while infile not empty
a = f.readline()
b = f.readline()
c = f.readline()
outfile.write("%s,%s,%s" % (a,b,c) )
If the data is manageable you could read it all into a list then use list
slicing to achieve the same
data = infile.readlines()
for start in range(len(data))[::3]: # get every third index
outfile.write("%s\t%s\t%s" % tuple(data[start :start+3]) )
I suspect you can do even clever things with itertools using groupby
and such, but I'm no itertools expert - its on my list of things to
learn... :-)
HTH,
--
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/
More information about the Tutor
mailing list