I am trying to append several lists each from a different csv files in Python. Here is the code I am using:
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')
It gives me the following error:
1-2
Traceback (most recent call last):
File "<stdin>", line 12, in <module>
TypeError: can only concatenate str (not "_io.TextIOWrapper") to str
I know that f = 'data'+str(from_)+'to'+str(to_)+'.csv' creates an _io.TextIOWrapper but I don't know how to turn it into a string so that I can read the file.
I have tried to read the csv files individually as below and it works fine:
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?