Pyhton csv阅读器:循环csv文件

bpsygsoo  于 2023-03-27  发布在  其他
关注(0)|答案(2)|浏览(154)

我有几个csv文件,它们被命名为:list_csv_X,其中X从0到5。我想用Python做一个循环来读取它们。
我现在正在手动操作:

for filepath in list_csv_0:
    with open(filepath,'r',encoding="utf8", errors='ignore') as csvfile:
        BLABLABLA
for filepath in list_csv_1:
    with open(filepath,'r',encoding="utf8", errors='ignore') as csvfile:
        BLABLABLA
for filepath in list_csv_2:
    with open(filepath,'r',encoding="utf8", errors='ignore') as csvfile:
        BLABLABLA

我该怎么做呢?
多谢了!

oxalkeyp

oxalkeyp1#

使用一个简单的 for 循环和一个f-string,如下所示:

def process(filename):
    with open(filename) as indata:
        pass # process file here

for fileno in range(6):
    with open(f'list_csv_{fileno}') as catalogue:
        for line in catalogue:
            process(line.strip())
5ssjco0h

5ssjco0h2#

如果我没理解错的话,你的6个项目都是一个 * 文件名列表 *,对吧?

我假设,因为你正在这样做,并说它目前有效:

for filepath in list_csv_0:

如果list_csv_0是一个文件名,这将导致错误,因为filepath值将是文件名的单个字符,而不是整个文件名。

可以循环列表

list_csvs = [list_csv_0,list_csv_1,list_csv_2,list_csv_3,list_csv_4,list_csv_5]

for list_csv in list_csvs:
    for filepath in list_csv:
        with open(filepath,'r',encoding="utf8", errors='ignore') as csvfile:
            BLABLABLA

相关问题