首页 > 解决方案 > 将来自csv的字符串组合成一行

问题描述

我正在尝试从只有一列的 csv 文件中读取。例如,我需要将所有字符串组合成一个,Row[1]=="Hallo."然后Row[2]=="Goodbye."组合成string=="Hallo. Goodbye.".

import csv

data=None
with open('reviews.csv',encoding='utf-8') as csv_file:
    csv_reader = csv.reader(csv_file, delimiter=',')
    line_count = 0
    for row in csv_reader:
        data2=(row[0])
        print(f'\n{data}.')
        line_count += 1
        data+=data2
    print(f'Processed {line_count} lines.')

我得到的当前错误是:

TypeError: unsupported operand type(s) for +=: 'NoneType' and 'str'

我已经搜索并阅读了一些帖子,但似乎无法理解。

标签: pythoncsv

解决方案


因为您要连接一堆字符串,所以请尝试使用带有简单生成器理解的字符串的 join 方法:

import csv

with open('reviews.csv',encoding='utf-8') as csv_file:
    csv_reader = csv.reader(csv_file, delimiter=',')
    data = "".join(row[0] for row in csv_reader if isinstance(row[0], str))

print(data)
print(f'Processed {csv_reader.line_num} lines')

请注意, csv_reader 在内部跟踪它已查看的行数。


推荐阅读