Python:如何将.csv文件中的信息导入到Python中,并将其作为元组内的列表? [英] Python: How to import information from a .csv file to python as a list with tuples inside?
问题描述
我是编程新手,所以请原谅我在编码方面的浅薄知识。我有一个可以用excel打开的.csv文件。每一行代表一个人的姓名和他们的详细信息(如地址,电话号码和年龄),每个细节在不同的列中。每当我进入新的行时,这都是另一个人的细节。
我想将这些信息导入python,使得每行(即该人的每个细节)都在1个元组中(每个细节用','分隔)我想要列表中的所有元组。所以基本上是一个列表里面有元组的列表。
我已经从打开文件开始编码,但不知道如何实现元组中所有人的每个细节细节以及列表中的所有元组。
def load_friends(f):
取名包含朋友信息的文件,如
介绍中所述,并返回一个列表,其中包含关于文件中的朋友
的信息。
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()
使用 csv
module 很简单:
在csv.reader(f,分隔符)中输入csv
打开('friends.csv','Ur')为f:
data = list =','))
data
是一个元组列表。
csv
m odule正确读取文件:
Smith,John,123
将被读为
('Smith,John' ,'123')
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')
这篇关于Python:如何将.csv文件中的信息导入到Python中,并将其作为元组内的列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!