n00bie help with file input and parsing
Greg Fortune
lists at gregfortune.com
Sun May 11 05:18:35 EDT 2003
Well, I just wrote a csv parser that will read that input file, but then
realized that wasn't the main question in your post ;o) Teach to me to
stay up this late..
jason wrote:
> Hi All,
>
> I am trying to write a program which takes the input from a csv file
> called input.txt. This file contains the following:
>
> "1","2","3","10064299","5","6","7","8","9"
> "1","2","3","10064862","5","6","7","8","9"
> "1","2","3","10064908","5","6","7","8","9"
> "1","2","3","10161170","5","6","7","8","9"
> "1","2","3","10161925","5","6","7","8","9"
> .....
> etc.
>
#quick, dirty way
lines = string.split(inp, '\n')
for x in lines:
print string.split(x, ',')[3]
> I also have files separate text files named QH10064299.txt,
> QH10064862.txt, QH10064908.txt etc.
>
> Basically, what I need to do is parse the "10064299" string from the
> input.txt file, strip the quotation marks, and add a QH and .txt onto
> the end so it matches one of other separate files. Then I need to
> open this file up in append mode, and add all the other information to
> it.
k, you should have the filename from above. Just open the file in append
mode..
>
> For example, if I pulled the 10064299 from the 1st line of input, I
> would then add the QH and .txt to make QH10064299.txt. Then I would
> open this file for appending and append:
>
> 1
> 2
> 3
> 10064299
> 5
> 6
> 7
> 8
> 9
>
> NB all quotes removed. Someone told me this could be written in about
> 10 lines of Python code, could anyone help me out? I have never
> before used Python.
cheating a little, you can do it in 5
lines = open('input.txt', 'r').readlines()
for x in lines:
out = open('QH' + string.split(x, ',')[3], + '.txt', 'a')
out.write(string.join(string.split(x, ','), '\n'))
out.close()
Do yourself a favor and check out the excellent documentation available at
python.org. Download a copy for yourself.. As you get more familiar with
the language, the Library Reference section is about the only thing you'll
ever need :)
Greg Fortune
Fortune Solutions
More information about the Python-list
mailing list