CSV Reader

Chris cwitts at gmail.com
Tue Feb 12 06:24:02 EST 2008


On Feb 12, 12:21 pm, Mike P <michael.pearm... at tangozebra.com> wrote:
> I did just try to post, but it doesn't look like it has appeared?
>
> I've used your advice Andrew and tried to use the CSV module, but now
> it doesn't seem to pick up the startswith command?
> Is this because of the way the CSV module is reading the data in?
> I've looked into the module description but i can't find anything that
> i hould be using?
>
> Can anyone offer an advice?
>
> Cheers again
>
> Mike
>
> working_CSV =  "//filer/common/technical/Research/E2C/Template_CSV/
> DFAExposureToConversionQueryTool.csv"
>
> save_file = "//filer/common/technical/Research/E2C/Template_CSV/
> CSV_Data2.csv"
>
> start_line=False
> import csv
> reader = csv.reader(open(working_CSV, "rb"))
> writer = csv.writer(open(save_file, "wb"))
> for row in reader:
>     if not start_line and record.startswith("'Transaction ID'"):
>         start_line=True
>     if start_line:
>     print row
>         writer.writerows(rows)
> #writer.close()

record won't have an attribute 'startswith' because record is a list
and startswith is a function of a string.
Also, your code isn't exactly clear on what you want to do, if it is
just "Find the first occurence of Transaction ID and pump the file
from then onwards into a new file" why not

output = open('output_file.csv','wb')
start_line = False
for each_line in open('input_file.csv','rb'):
    if not start_line and each_line.startswith("'Transaction ID'"):
        start_line = True
    if start_line:
        output.write( each_line )
output.close()

also, if you need a line number for any purposes, take a look at
enumerate() and with that it will return a counter and your data, for
eg. 'for (line_num, each_line) in enumerate(input_file):'.  Counting
starts @ zero though so you would need to add 1.



More information about the Python-list mailing list