尝试从TSV行读取5列时解压缩错误

时间:2015-06-28 18:11:27

标签: python csv

我有一个包含5列行的TSV文件。我想将每行的列写入单独文件中的行。第一列是文件名。我尝试了下面的代码,但得到以下错误。

  filename, text, missspellings, uncertainty, weekgoal = row
ValueError: need more than 2 values to unpack
import csv
import sys

csv.field_size_limit(sys.maxsize)

with open("id_descr.tsv") as f:
    reader     = csv.reader(f, delimiter="\t")
    fieldnames = next(reader)
    for row in reader:
        filename, text, missspellings, uncertainty, weekgoal = row
        print('filename: {}'.format(filename))
        print('text: {}'.format(text))
        print('missspellings: {}'.format(missspellings))
        print('uncertainty: {}'.format(uncertainty))
        print('weekgoal: {}'.format(week goal))

1 个答案:

答案 0 :(得分:0)

至少有一行少于5列。而不是将每列分配给变量,只需写出您获得的任何列。而不是打印值,而是根据第一列中的文件名将它们写入文件。您可以使用从标题中读取的字段名,而不是再次将其写出来。

data_columns = next(reader)[1:]  # skip first column header, the filename

for row in reader:
    if not row:
        continue  # need at least filename

    with open(row[0], 'w') as out:  # make separate files
        for name, value in zip(data_columns, row[1:]):  # write columns except filename
            out.write('{}: {}'.format(name, value))