2

I am new to programming so please excuse my shallow knowledge with coding. I have a .csv file that I can open with excel. Each row represents a person's name and their details (like address, phone number and age) with each detail in different columns. Whenever I move onto a new row it is another person's detail.

I want to import this information into python such that each row (i.e. every detail of that person) is in 1 tuple (with each detail separated with a ',') and I want all the tuples in a list. So basically a list with tuples inside them.

I have started with the coding from opening the file but just don't know how to implement each detail detail of the person in a tuple and all the tuples in a list. I am using Python 2.7.

def load_friends(f):
"""
Takes the name of a file containing friends information as described in the
introduction and returns a list containing information about the friends
in the file.

load_friends(var) -> list

"""

openfile = open('friends.csv', 'Ur')
if f == 'friends.csv':
    openfile = open('friends.csv', 'Ur')
    lines = openfile.readlines()
    print lines
    openfile.close()
user2248286
  • 21
  • 1
  • 1
  • 3
  • Please provide sample csv data that are you trying to parse. Anyway, you should definitely use [csv](http://docs.python.org/2/library/csv.html) module. – alecxe Apr 05 '13 at 09:50

2 Answers2

11

With the csv module it is quite simple:

import csv

with open('friends.csv', 'Ur') as f:
    data = list(tuple(rec) for rec in csv.reader(f, delimiter=','))

data is a list of tuples.

The csv module reads the files correctly:

"Smith, John",123

will be read as

('Smith, John', '123')
eumiro
  • 207,213
  • 34
  • 299
  • 261
  • Hello!! Thanks for the fast reply!! I was fiddling with my original code and the code you suggested. After a while of figuring where to properly insert the code you gave me I got something similar to what you said the final execution should look like. However my result of the details of each person is given in square brackets [] not the tuple, curly brackets (). My final result is lists in a list. Like this:[['John Cleese', 'Ministry of Silly Walks', '5555421', '27 October'], ['Eric Idle', 'Spamalot', '55553311', '29 March']]. Can you please tell me where might I have gone wrong? Thank you!! – user2248286 Apr 05 '13 at 14:33
  • @user2248286 - sorry, you're right - the `csv.reader` returns lists. Please see my edited answer, which will return a list of tuples. – eumiro Apr 08 '13 at 07:19
0
import csv
DIR = 'your dicrectory path'
openfile = csv.DictReader(open(DIR + '/file_name.csv', 'r'))
print .fieldnames
for p in filename:
    try:
        p = dict((k.strip().strip('\\t'), v) for k, v in p.iteritems() if v.lower() != 'null')
except AttributeError, e:
    print e
    print p
    raise Exception()
print p.get('Name'),p.get('Details')
Mohan
  • 9
  • 7