Answer the question
In order to leave comments, you need to log in
How to read csv file by python script?
How to read csv file by python script?
import csv
with open('some.csv', 'rb') as f:
reader = csv.reader(f)
for row in reader:
print row
python2 test.py
Traceback (most recent call last):
File "test.py", line 1, in <module>
import csv
File "/home/miruss/virtualbox/csv.py", line 4, in <module>
f = open(sys.argv[1], 'rt')
IndexError: list index out of range
Answer the question
In order to leave comments, you need to log in
If the data from .csv is being loaded in tabular form, I advise you to try pandas .
Example:
import pandas as pd
infile='some.csv'
df=pd.read_csv(infile)
print(df.head())
Wrote this:
def read_attributes(filename):
with open(filename, 'r') as f:
header = f.readline().strip()
attributes = [attr.strip() for attr in header.split(",")]
return attributes
def read_data(filename, attributes):
with open(filename) as f:
lines = [line.strip() for line in f.readlines()]
del lines[0] # header :)
data = []
for line in lines:
data.append(dict(zip(attributes, [datum.strip() for datum in line.split(",")])))
return data
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question