I want to import CSV files in a python script. Column and row numbers are not fixed , first row contains name of the variables and next rows are values of those variables. I am new to Python, any help is appreciated. thanks.
3 Answers
import csv
csv_reader = csv.reader(open(path_file + filename, 'rb'))
fields = []
data = []
for i, row in enumerate(csv_reader):
if i < 1:
item = str(row[0]).split(';')
for elem in item:
fields.append(elem)
else:
obj_val = {}
items = str(row[0]).decode(codes).split(';')
for i, item in enumerate(items):
obj_val[fields[i]] = item
data.append(obj_val)
- fields - field
- data - rows from csv
So as not to just give out a homework answer, but to still point you in the right direction; import the CSV module. If you're using Python 3.5 here's the link to the doc. If you want to see the doc for a different version, use the drop-down on the top-left of the page to select it.
Anyway...
You'll want to open the CSV file like you would any other, then use the CSV module to read the content. Iterating over each row in the file will return you a list of strings; which are the contents of that row.
For example:
['Header 1', 'Header 2', 'Header 3'...]
['A1', 'A2', 'A3'...]
['B1', 'B2', 'B3'...]
['C1', 'C2', 'C3'...]
...
First of all, at the top of the code do import csv
After that you need to set a variable name; this is so you can open the CSV file. For example, data=open('CSV name', 'rt')
You will need to fill in where it says CSV name. That's how you open it.
To read a CSV file, you set another variable. For example, data2=csv.reader(data)