【问题标题】:Read all .csv files within the folder without having a fixed name? [duplicate]在没有固定名称的情况下读取文件夹中的所有 .csv 文件? [复制]
【发布时间】:2021-09-18 08:17:47
【问题描述】:

我在与我的 python 脚本相同的文件夹中有一个 users.csv 文件。 我用它来阅读文件夹:

users = []
with open(r"users.csv", encoding='UTF-8') as f: 

有没有办法自动读取目录中的任何 .csv 文件而无需输入"users.csv"

不知道如何措辞,但我会给出一些上下文。

我有 10 个文件夹,所有文件夹里面都有 1 个 users.csv 文件以及读取此类文件的脚本。每次我必须切换 .csv 文件时,我必须在所有文件夹中重命名它 10 次,以便脚本读取它。如果文件是 csv 格式,有什么方法可以自动读取文件?

【问题讨论】:

标签: python python-3.x


【解决方案1】:

你可以这样做:

import os
for file in os.listdir("."):
    if file.endswith(".csv"):
        #read it

查看所有子目录:

for root, dirs, _ in os.walk("."):
    for d in dirs:
        files = [os.path.join(root, d, f) for f in os.listdir(os.path.join(root, d)) if f.endswith(".csv")]
        if len(files)>0:
            for f in files:
                #read f

【讨论】:

  • 请删除此答案,如果它不在重复目标中,请将其发布在那里
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-12-25
  • 1970-01-01
  • 1970-01-01
  • 2017-10-19
  • 1970-01-01
相关资源
最近更新 更多