Pierce
Pierce

Reputation: 383

How to import data from csv using python

I am new to python.
I am facing lot of difficulty in finding a way to import data from csv file into my python code.
My csv file is not comma separated data.
I am using Python 2.7.

Upvotes: 0

Views: 12092

Answers (3)

David Hagan
David Hagan

Reputation: 1166

This is one of the things that pandas is absolutely fantastic at. I would highly recommend installing and using pandas rather than just the csv module.

import pandas as pd
df = pd.read_csv(filename)

You can then view the details of your new dataframe by simply typing

df.info()

Above, you mentioned that you wanted to view the 4th column of the 3rd row. With a dataframe, you could get that by typing

df[3]['Column 4']

Upvotes: 1

JC_CL
JC_CL

Reputation: 2608

It would be really helpful to have some more info about what data you want to import and why!

To just get a small text file into python, and then reading around in it a bit, here's what I'd do:

current_csv = csv_list[somecounter]  
#this is assuming you have a whole directory of files 
#and you implemt some file picking beforehand

infile= open(current_csv, 'r')
import csv
table = [] #initialize a table

#initialize a counter for the rows
rows=0

#read the first 50 lines of the csv into table
#depending on your file, you should probably implement some logic to see how many rows you need
for row in csv.reader(infile):
     rows+=1
     if rows<50:
         table.append(row)
infile.close()

With the table, you can now do things such as (assuming you have a fixed structure of you CSV) Filename = table[0] or search for stuff by looping through your table.

Depending you the type of CSV's, I also strongly suggest you look into pandas

For me, it's CSV import and subsequent modification and analysis functions are much easier and more capable than standard pythons offerings.

Upvotes: 0

ajay_t
ajay_t

Reputation: 2385

Lets say your people.csv file is :

id,name,age,height,weight
1,Alice,20,62,120.6
2,Freddie,21,74,190.6
3,Bob,17,68,120.0

Following code will return dictionary.

import csv
input_file = csv.DictReader(open("people.csv"))
for row in input_file:
    print row

Output:

{'age': '20', 'height': '62', 'id': '1', 'weight': '120.6', 'name': 'Alice'}
{'age': '21', 'height': '74', 'id': '2', 'weight': '190.6', 'name': 'Freddie'}
{'age': '17', 'height': '68', 'id': '3', 'weight': '120.0', 'name': 'Bob'}

This is very efficient way as csv is represented in dictionary. Let's say, you want to get details from first row, then you can simply get it like row['age'] and so on

Upvotes: 1

Related Questions