首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Python将在其中遍历多个文件夹和处理文件

Python将在其中遍历多个文件夹和处理文件
EN

Stack Overflow用户
提问于 2022-07-05 15:45:12
回答 1查看 19关注 0票数 0

我有多个文件夹,每个文件夹包含大约5-10个文件.我要做的是在完成前几个文件夹中的文件处理后转到下一个文件夹,然后开始处理新的文件。我有这样的代码:

代码语言:javascript
复制
for root, dirs, files in os.walk("Training Sets"): #Path that contains folders
    for i in dirs: #if I don't have this, an error is shown in line 4 that path needs to be str and not list
        for file in i: #indexing files inside the folders
            path = os.path.join(i, files) #join path of the files
            dataset = pd.read_csv(path, sep='\t', header = None) #reading the files
            trainSet = dataset.values.tolist() #some more code
            editedSet = dataset.values.tolist() #some more code
            #rest of the code...

问题是它什么也做不了。如果我添加打印以进行调试,甚至不会打印。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-07-05 16:15:08

首先,确保您位于正确的顶级目录(即包含“培训集”的目录)。您可以使用os.path.abspath(os.curdir)来检查这一点。否则,代码什么也不做,因为它找不到要遍历的目录。

os.walk为您执行目录遍历操作。关键是理解根(当前目录的路径)、dirs (子目录列表)和文件(当前目录中的文件列表)。你其实不需要脏东西。

所以你的代码是两个循环:

代码语言:javascript
复制
>>> for root, dirs, files in os.walk("New Folder1"): #Path that contains folders
...     for file in files: #indexing files inside the folders
...             path = os.path.join(root, file) #join path of the files
...             print(path) # Your code here
...
New Folder1\New folder1a\New Text Document.txt
New Folder1\New folder1b\New Text Document2.txt
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72872207

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档