M
M
mirus2014-12-02 01:45:43
linux
mirus, 2014-12-02 01:45:43

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

gives such an error
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

I don't understand what is the reason for the error.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
M
Max, 2014-12-02
@mbelskiy

So try:
f = open(sys.argv[0], 'rt')

L
lPolar, 2014-12-02
@lPolar

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())

K
klamer, 2014-12-05
@klamer

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 question

Ask a Question

731 491 924 answers to any question