sdunnim
sdunnim

Reputation: 221

Reading and splitting a .csv file, which contains strings with commas in

I have a .csv file which looks something like this:

1,2,"a,b",3
4,"c,d",5,6

Which I am reading and storing in an array like this:

with open(filename, 'r') as f:
    data = f.readlines()
data = [line.split(',') for line in data]

Which results in an array like this:

[['1','2','"a','b"','3']['4','"c','d"','5','6']]

HOWEVER, I would like to keep the items within double quotes such as "a,b" in one element of the data array (which is how they are opened in Excel), like this:

[[1,2,'a,b',3][4,'c,d',5,6]]

Is there an easy way to achieve this in Python?

Edit: preferably without using the csv module if possible?

Upvotes: 2

Views: 2918

Answers (2)

wasif
wasif

Reputation: 15478

Using csv module:

import csv

with open('test.csv') as file:
    reader = csv.reader(file)
    
data = [row for row in reader]

Upvotes: 3

Thierry Lathuille
Thierry Lathuille

Reputation: 24232

You should use the csv module:

import csv

with open('test.csv') as f:
    reader = csv.reader(f)
    
    for row in reader:
        print(row)

Output:

['1', '2', 'a,b', '3']
['4', 'c,d', '5', '6']

Or, if you don't want to read lines lazily and want all in a single list, as in your question, you can simply do:

with open('test.csv') as f:
    reader = csv.reader(f)
    data = list(reader)

print(data)        
# [['1', '2', 'a,b', '3'], ['4', 'c,d', '5', '6']]   

Upvotes: 3

Related Questions