【发布时间】:2020-07-03 18:35:35
【问题描述】:
我正在尝试从 Python 中的不同 csv 文件中附加几个列表。这是我正在使用的代码:
from_ls = [1,2,3,4,5]
to_ls = [2,3,4,5,6]
mylists = []
for i in range(len(from_ls)):
from_ = from_ls[i]
to_ = to_ls[i]
print(str(from_)+'-'+str(to_))
f = 'data'+str(from_)+'to'+str(to_)+'.csv'
if os.path.exists(f):
with open('data'+str(from_)+'to'+str(to_)+'.csv') as f:
reader = csv.reader(f)
mylists.extend(reader)
print('file '+f+' append successfully')
else:
print('file '+f+' not found')
它给了我以下错误:
1-2
Traceback (most recent call last):
File "<stdin>", line 12, in <module>
TypeError: can only concatenate str (not "_io.TextIOWrapper") to str
我知道f = 'data'+str(from_)+'to'+str(to_)+'.csv' 创建了一个_io.TextIOWrapper,但我不知道如何将其转换为字符串以便我可以读取文件。
我尝试如下单独读取 csv 文件,它工作正常:
i=0
from_ = from_ls[i]
to_ = to_ls[i]
with open('data'+str(from_)+'to'+str(to_)+'.csv') as f:
reader = csv.reader(f)
mylists = list(reader)
【问题讨论】:
-
什么是
text? -
我已更正:它实际上是 mylists
标签: python python-3.x list csv opencsv