[英]How do you walk through the directories using python?
我有一個文件夾叫做notes,自然會被歸類到文件夾中,在這些文件夾中也會有子目錄的子文件夾。 現在我的問題是我有一個遍歷 3 個子目錄級別的函數:
def obtainFiles(path):
list_of_files = {}
for element in os.listdir(path):
# if the element is an html file then..
if element[-5:] == ".html":
list_of_files[element] = path + "/" + element
else: # element is a folder therefore a category
category = os.path.join(path, element)
# go through the category dir
for element_2 in os.listdir(category):
dir_level_2 = os.path.join(path,element + "/" + element_2)
if element_2[-5:] == ".html":
print "- found file: " + element_2
# add the file to the list of files
list_of_files[element_2] = dir_level_2
elif os.path.isdir(element_2):
subcategory = dir_level_2
# go through the subcategory dir
for element_3 in os.listdir(subcategory):
subcategory_path = subcategory + "/" + element_3
if subcategory_path[-5:] == ".html":
print "- found file: " + element_3
list_of_files[element_3] = subcategory_path
else:
for element_4 in os.listdir(subcategory_path):
print "- found file:" + element_4
請注意,這仍然是一項正在進行的工作。 在我看來它非常丑陋......我在這里試圖實現的是遍歷所有文件夾和子文件夾並將所有文件名放入名為“list_of_files”的字典中,名稱為“key”,並且完整路徑作為“值”。 該函數還不能完全工作,但想知道如何使用 os.walk 函數來做類似的事情?
謝謝
根據您的簡短描述,這樣的事情應該有效:
list_of_files = {}
for (dirpath, dirnames, filenames) in os.walk(path):
for filename in filenames:
if filename.endswith('.html'):
list_of_files[filename] = os.sep.join([dirpath, filename])
另一種方法是使用生成器,以@ig0774 的代碼為基礎
import os
def walk_through_files(path, file_extension='.html'):
for (dirpath, dirnames, filenames) in os.walk(path):
for filename in filenames:
if filename.endswith(file_extension):
yield os.path.join(dirpath, filename)
進而
for fname in walk_through_files():
print(fname)
我多次遇到過這個問題,但沒有一個答案讓我滿意 - 所以為此創建了一個腳本。 在遍歷目錄時,Python 使用起來非常麻煩。
以下是它的使用方法:
import file_walker
for f in file_walker.walk("/a/path"):
print(f.name, f.full_path) # Name is without extension
if f.isDirectory: # Check if object is directory
for sub_f in f.walk(): # Easily walk on new levels
if sub_f.isFile: # Check if object is file (= !isDirectory)
print(sub_f.extension) # Print file extension
with sub_f.open("r") as open_f: # Easily open file
print(open_f.read())
你可以這樣做:
list_of_files = dict([ (file, os.sep.join((dir, file)))
for (dir,dirs,files) in os.walk(path)
for file in files
if file[-5:] == '.html' ])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.