【发布时间】:2018-06-07 03:00:25
【问题描述】:
我有数千个内部格式相同的 csv 文件。行通常有八列,格式如下:
row1 = ['string in column 0', 'string in column 1', 'string in column 2'...]
row2 = ['string in column 0', 'string in column 1', 'string in column 2'...]
row3 = ['string in column 0', 'string in column 1', 'string in column 2'...]
对于每个文件,我想读取某些行并输出按行分隔的元组列表。例如,文件在前八列中有字符串,我希望最终输出为:
list_of_tuples = [('row1_col0','row1_col2','row1_col5','row1_col6'),('row2_col0','row2_col2','row2_col5','row2_col6'),...]
并不是所有的行都有四个值,所以我害怕生成四个列表,然后在它们被读入后构建一个元组。
到目前为止我构建的函数是
import csv
def list_of_tuples_from_csv(filepath_to_csv):
total_text = []
with open(file path_to_csv, 'r') as f:
reader = csv.reader(f)
for row in reader:
total_text.append(tuple(row[0],row[2],row[5],row[6]))
total_posts = list(set(total_text))
return total_posts
但我得到一个错误阅读
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 6, in list_of_tuples_from_csv
TypeError: tuple() takes at most 1 argument (4 given)
【问题讨论】:
-
请发布数据样本
-
发布完整的回溯,包括它发生的行。
-
在力所能及的范围内回复了这两个问题。谢谢!
标签: python python-3.x csv tuples