阅读CSV为文本文件,它标记化

问题描述 投票:0回答:1

我有一个以前疑问,有太多的部件,所以我敦促分解任务。首先我要读我的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'

这是什么意思,一个如何解决这个问题?

python-3.x csv tokenize
1个回答
0
投票

使用csv module实例化一个reader对象。

我不是100%肯定,你想要达到的目标,但下面的代码会从您的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)的实例化需要的文件,而不是文件名作为参数。

© www.soinside.com 2019 - 2024. All rights reserved.