csv怎么导入python_Python:如何将.csv文件中的信息导入到Python中,并将其作为元组内的列表?...

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

解决方案

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值