【问题标题】:Python: How to import information from a .csv file to python as a list with tuples inside?Python:如何将 .csv 文件中的信息作为包含元组的列表导入 python?
【发布时间】:2013-03-27 15:42:08
【问题描述】:

我是编程新手,所以请原谅我对编码的浅薄知识。我有一个可以用 excel 打开的 .csv 文件。每行代表一个人的姓名及其详细信息(如地址、电话号码和年龄),每个详细信息位于不同的列中。每当我移动到新行时,它都是另一个人的详细信息。

我想将此信息导入 python,这样每一行(即那个人的每个细节)都在 1 个元组中(每个细节用“,”分隔),我想要一个列表中的所有元组。所以基本上是一个包含元组的列表。

我从打开文件开始编码,但不知道如何实现元组中人员的每个细节细节以及列表中的所有元组。我正在使用 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()

【问题讨论】:

  • 请提供您尝试解析的示例 csv 数据。无论如何,你绝对应该使用csv 模块。

标签: python function import


【解决方案1】:

使用csv module 非常简单:

import csv

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

data 是一个元组列表。

csv 模块正确读取文件:

"Smith, John",123

将被读作

('Smith, John', '123')

【讨论】:

  • 你好!感谢您的快速回复!我正在摆弄我的原始代码和您建议的代码。在弄清楚在哪里正确插入你给我的代码之后,我得到了类似于你所说的最终执行应该是什么样子的东西。但是,我对每个人的详细信息的结果是在方括号 [] 中给出的,而不是在元组大括号 () 中。我的最终结果是列表中的列表。像这样:[['John Cleese', 'Ministry of Silly Walks', '5555421', '10 月 27 日'], ['Eric Idle', 'Spamalot', '55553311', '3 月 29 日']]。你能告诉我我哪里出错了吗?谢谢!!
  • @user2248286 - 抱歉,你是对的 - csv.reader 返回列表。请查看我编辑的答案,它将返回一个元组列表。
【解决方案2】:
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')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-21
    • 1970-01-01
    • 2022-01-07
    • 2015-07-06
    • 2019-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多