Crak
Crak

Reputation: 91

Trouble splitting a String with Python

I'm desperatly trying to split a string using Python but the text file I need to parse is a little bit tricky:

I did the following:

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

This actually should make the job right ?

Ok now the tricky part: I have some field that contains comma inside like the one below:

"(CONTRACTS OF 5,000 BUSHELS)"

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

How can I ask python to use comma as a delimiter but not when they are enclosed by "" ?

Thank you in advance for your answers

Crak

Upvotes: 3

Views: 1012

Answers (3)

Corey Goldberg
Corey Goldberg

Reputation: 60604

you can use the 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

Upvotes: 4

Ferdinand Beyer
Ferdinand Beyer

Reputation: 67147

Your data is in a pretty common format -- Comma Separated Values (CSV). Instead of writing yet another parser, consider using the built-in csv module.

Upvotes: 10

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798606

CSV files should be handled with csv.

Upvotes: 5

Related Questions