我想为目录中的每个文件在python中运行循环。目录名称将通过单独的文件(folderlist.txt)传递。
在我的主文件夹(/ user /)中,每天都会添加新文件夹。所以我想为给定文件夹中的每个文件运行循环。并且不想针对已经通过循环运行了文件的文件夹运行。我正在考虑维护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模块,但看起来循环运行的次数比文件夹中文件的运行次数多。请提供输入。
答案 0 :(得分:3)
尝试将os.walk(dir)
的{{1}}更改为目录中所有元素的列表
os.listdir(dir)
希望有帮助
答案 1 :(得分:0)
*有关功能进入模块os的帮助:
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)可以列出该目录中所有文件和文件夹的列表。