【问题标题】:Append lists from different csv files in Python在 Python 中附加来自不同 csv 文件的列表
【发布时间】: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


【解决方案1】:

我已尝试重现您的错误,但无法重现。但是我发现了一些错误。

import os
import 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_))
    fname = 'data'+str(from_)+'to'+str(to_)+'.csv'
    if os.path.exists(fname):
        with open(fname) as f:
            reader = csv.reader(f)
            mylists.extend(reader)
        print('file '+fname+' append successfully')
    else:
        print('file '+fname+' not found')

我这里没有 csv 文件。试试看它是否更正了你的代码。

【讨论】:

    【解决方案2】:

    在这里:

        print('file '+f+' append successfully')
    else:
        print('file '+f+' not found')
    

    f 是您将open('data'+str(from_)+'to'+str(to_)+'.csv') 分配给的变量。

    虽然您有f = 'data'+str(from_)+'to'+str(to_)+'.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_))
        fn = 'data'+str(from_)+'to'+str(to_)+'.csv' # Note the change of variable name
        if os.path.exists(fn): # And here
            with open('data'+str(from_)+'to'+str(to_)+'.csv') as f:
                reader = csv.reader(f)
                mylists.extend(reader)
            print('file '+fn+' append successfully') # Here
        else:
            print('file '+fn+' not found') # Here also
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-10-23
      • 1970-01-01
      • 1970-01-01
      • 2017-01-21
      • 2014-05-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多