[英]In python, how to get the path to all the files in a directory, including files in subdirectories, but excluding path to subdirectories
我有一個包含文件夾和子文件夾的目錄。 每個路徑的末尾都有文件。 我想制作一個txt文件,其中包含所有文件的路徑,但不包括文件夾的路徑。
我從“ 獲取當前目錄中所有子目錄的列表”中嘗試了此建議,我的代碼如下所示:
import os
myDir = '/path/somewhere'
print [x[0] for x in os.walk(myDir)]
它給出了所有元素(文件和文件夾)的路徑,但是我只想要文件的路徑。 有什么想法嗎?
os.walk(path)返回三個元組的父文件夾,子目錄和文件。
所以你可以這樣:
for dir, subdir, files in os.walk(path):
for file in files:
print os.path.join(dir, file)
os.walk方法在每次迭代中為您提供目錄,子目錄和文件,因此,當您遍歷os.walk時,您將必須遍歷文件並將每個文件與“ dir”組合。
為了執行此組合,您要做的是在目錄和文件之間執行os.path.join
。
這是一個簡單的示例,可幫助說明os.walk的遍歷方式
from os import walk
from os.path import join
# specify in your loop in order dir, subdirectory, file for each level
for dir, subdir, files in walk('path'):
# iterate over each file
for file in files:
# join will put together the directory and the file
print(join(dir, file))
如果只需要路徑,則將過濾器添加到列表理解中,如下所示:
import os
myDir = '/path/somewhere'
print [dirpath for dirpath, dirnames, filenames in os.walk(myDir) if filenames]
然后,這只會添加包含文件的文件夾的路徑。
def get_paths(path, depth=None):
for name in os.listdir(path):
full_path = os.path.join(path, name)
if os.path.isfile(full_path):
yield full_path
else:
d = depth - 1 if depth is not None else None
if d is None or d >= 0:
for sub_path in get_paths(full_path):
yield sub_path
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.