Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/bash/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用Python为目录中的每个文件运行for循环_Python_Bash - Fatal编程技术网

使用Python为目录中的每个文件运行for循环

使用Python为目录中的每个文件运行for循环,python,bash,Python,Bash,我想在python中为目录中的每个文件运行for循环。目录名将通过一个单独的文件folderlist.txt传递 在我的主文件夹/user/中,每天都会添加新文件夹。所以我想为给定文件夹中的每个文件运行for循环。并且不希望针对已通过循环运行的文件的文件夹运行。我正在考虑维护folderlist.txt,它每天只包含新添加的文件夹的文件夹名,然后将这些文件夹名传递给for循环。 例如,在我的主路径/用户/下,我们可以看到以下文件夹: 每个文件夹中存在的文件都列在文件夹名称的下面,这只是为了说明问

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

在我的主文件夹/user/中,每天都会添加新文件夹。所以我想为给定文件夹中的每个文件运行for循环。并且不希望针对已通过循环运行的文件的文件夹运行。我正在考虑维护folderlist.txt,它每天只包含新添加的文件夹的文件夹名,然后将这些文件夹名传递给for循环。 例如,在我的主路径/用户/下,我们可以看到以下文件夹: 每个文件夹中存在的文件都列在文件夹名称的下面,这只是为了说明问题

(day 1)
folder1
file1, file2, file3

folder2
file4, file5

folder3
file6

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

folder5
file11, file12
我尝试在上面的代码中使用os.walk和glob模块,但循环运行的次数似乎比文件夹中的文件要多。请提供输入。

尝试将os.walkdir更改为os.listdirdir,这将为您提供目录中所有元素的列表

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

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

希望对您有所帮助

*有关功能步入式模块操作系统的帮助:

walktop,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).*
因此,第二个循环中的文件在dirpathstring、dirnameslist、filenameslist上迭代。
使用os.listdirdir会列出dir as列表中的所有文件和文件夹。

嘿,那么,您希望发生什么,但实际发生了什么?你能编辑你的帖子来继续运行上述代码的结果吗?关于os.listdir:中的文件,我想你指的是文件而不是文件。
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).*