簡體   English   中英

使用Python為目錄中的每個文件運行for循環

[英]Run the for loop for each file in directory using Python

我想在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模塊,但看起來循環運行的次數比文件夾中的文件多。 請提供意見。

嘗試更改os.listdir(dir) os.walk(dir) ,它將為您提供dir中所有元素的列表

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)

希望能幫助到你

*幫助函數在模塊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(字符串),dirnames(列表),文件名(列表)上進行迭代。 使用os.listdir(dir)給出dir中列出的所有文件和文件夾列表。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM