以文本文件形式读取CSV并将其标记化

时间:2019-02-05 03:56:54

标签: python-3.x csv tokenize

我之前的问题有太多的组成部分,因此敦促我分解任务。首先,我将以文本文件形式读取CSV并标记其中的数据。当我出现错误时。

csv_file = 'Annual Budget.csv'
txt_file = 'Annual Budget.txt'
with open(txt_file, 'w') as my_output_file:
    with open(csv_file, 'r') as my_input_file:
        for row in csv_file.reader(my_input_file):
            my_output_file.write(" ".join(row)+'\n')

这是错误(输出):

line 46, in <module>
    for row in csv_file.reader(my_input_file):
AttributeError: 'str' object has no attribute 'reader'

这是什么意思,怎么解决呢?

1 个答案:

答案 0 :(得分:0)

使用csv module实例化reader对象。

我不确定要实现什么目标,但是下面的代码将从您的CSV文件中创建一个文本文件,其中的单元格以空格逐行连接:

import csv

csv_file = 'Annual Budget.csv'
txt_file = 'Annual Budget.txt'
with open(txt_file, 'w') as my_output_file:
    with open(csv_file, 'r') as my_input_file:
        reader = csv.reader(my_input_file)
        for row in reader:
            my_output_file.write(" ".join(row)+'\n')

请注意,CSV阅读器对象(reader)的实例采用文件,而不是文件名作为参数。