Python line break problem

I am desperately trying to break a string using Python, but the text file I need for parsing is a bit more complicated:

  • A text file is a comma delimited data file

I have done the following:

import fileinput
for line in fileinput.input("sample.txt"):
data = line.strip().split(',')
pass

Does this really have to do the job right?

Ok now the tricky part: I have a field containing a comma inside, as shown below:

"(CONTRACTS OF 5,000 BUSHELS)"

using my code, the script will also split this field by 2.

How can I ask python to use a comma as a separator, but not when they are enclosed in "???

Thank you in advance for your answers.

Crack

+3
source share
3 answers

- , (CSV). , , csv.

+10

CSV csv.

+5

you can use csv module

import csv

with open('sample.txt', 'rb') as f:
    reader = csv.reader(f)
    for row in reader:
        # each row is a list of items,
        # corresponding to each row in your file,
        # including commas for quoted items
+4
source

All Articles