【问题标题】:Run the for loop for each file in directory using Python使用 Python 为目录中的每个文件运行 for 循环
【发布时间】:2019-02-13 05:06:27
【问题描述】:

我想在 python 中为目录中的每个文件运行 for 循环。目录名称将通过一个单独的文件 (folderlist.txt) 传递。

在我的主文件夹 (/user/) 中,每天都会添加新文件夹。所以我想为给定文件夹中的每个文件运行 for 循环。并且不想针对文件已经通过循环运行的文件夹运行。我正在考虑维护 folderlist.txt ,其中每天仅包含新添加的文件夹的文件夹名称,然后将其传递给 for 循环。
例如,在我的主路径 (/user/) 下,我们看到以下文件夹:
(每个文件夹中存在的文件都列在文件夹名称下方,只是为了给出想法)

(day 1)
folder1
file1, file2, file3

folder2
file4, file5

folder3
file6

(day 2)
folder4
file7, file8, file9, file10

folder5
file11, file12
import os
with open('/user/folderlist.txt') as f:
    for line in f:
        line=line.strip("\n")

        dir='/user/'+line
        for files in os.walk (dir):
            for file in files:
                print(file)
#        for filename in glob.glob(os.path.join (dir, '*.json')):
#                print(filename)

我尝试在上述代码中使用 os.walk 和 glob 模块,但看起来循环运行的次数比文件夹中的文件多。请提供意见。

【问题讨论】:

  • 嘿,那么,您期望会发生什么,但实际发生了什么?您能否编辑您的帖子以包含运行上述代码的结果?

标签: python bash


【解决方案1】:

尝试将os.walk(dir) 更改为os.listdir(dir),这将为您提供目录中所有元素的列表

import os
with open('/user/folderlist.txt') as f:
    for line in f:
        line = line.strip("\n")

        dir = '/user/' + line
        for file in os.listdir(dir):
            if file.endswith("fileExtension")
                print(file)

希望对你有帮助

【讨论】:

  • 关于for files in os.listdir (dir):,我想你的意思是file而不是files
【解决方案2】:

*模块os中函数walk的帮助:

walk(top, topdown=True, onerror=None, followlinks=False) 目录树生成器。

For each directory in the directory tree rooted at top (including top
itself, but excluding '.' and '..'), yields a 3-tuple

    dirpath, dirnames, filenames

dirpath is a string, the path to the directory.  dirnames is a list of
the names of the subdirectories in dirpath (excluding '.' and '..').
filenames is a list of the names of the non-directory files in dirpath.
Note that the names in the lists are just names, with no path components.
To get a full path (which begins with top) to a file or directory in
dirpath, do os.path.join(dirpath, name).*

因此,第二个循环中的文件在 dirpath(string)、dirnames(list)、filenames(list) 上进行迭代。 使用 os.listdir(dir) 会给出 dir 中所有文件和文件夹的列表。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-07-31
    • 1970-01-01
    • 1970-01-01
    • 2020-11-22
    • 2016-03-11
    • 2012-10-16
    • 1970-01-01
    • 2018-09-29
    相关资源
    最近更新 更多