[英]How to print the subdirectory name using python
我的代碼掃描“監視器”文件夾下的目錄和子目錄,但是以某種方式我無法打印子目錄名稱。
Monitors是父目錄,Dell是子目錄,io是Dell下的文件。
-Monitors
-------- Cab.txt
--- Dell
-------- io.txt
-------- io2.txt
我的父目錄和代碼
parent_dir = 'E:\Logs\Monitors'
def files(parent_dir):
for file in os.listdir(parent_dir):
if os.path.isfile(os.path.join(parent_dir, file)):
yield file
def created(file_path):
if os.path.isfile(file_path):
file_created = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(os.path.getctime(file_path)))
return file_created
len = (item for item in files(parent_dir))
str = ""
for item in len:
str +="File Name: " + os.path.join('E:\\Logs\\Monitors\\', item) + "\n" \
+ "File Created on: " + created(os.path.join('E:\\Logs\\Monitors\\', item)) + "\n" \
print str;
產量
E:Logs\Monitors\Cab.txt
E:Logs\Monitors\io.txt
E:Logs\Monitors\io2.txt
我想要的輸出
E:Logs\Monitors\Cab.txt
E:Logs\Monitors\Dell\io.txt
E:Logs\Monitors\Dell\io2.txt
我嘗試在path.join中使用變量,但以錯誤結束。
而不是使用os.listdir()
,而是使用os.walk()
遍歷樹中的所有目錄:
for dirpath, dirnames, filenames in os.walk(parent_dir):
for filename in filenames:
full_path = os.path.join(dirpath, filename)
print 'File Name: {}\nFile Created on: {}\n'.format(
full_path, created(full_path))
os.walk()
每次迭代都會為您提供有關一個目錄的信息。 dirpath
是該目錄的完整路徑,而dirnames
和filenames
是該位置中目錄和文件filenames
的列表。 只需在文件名上使用循環即可處理每個文件名。
if os.path.isfile(os.path.join(parent_dir, file)):
str +="File Name: " + os.path.join('E:\\Logs\\Monitors\\', item) + "\n" \
該行似乎繞過了子目錄名稱。 您基本上是在做以下事情;
If file is file:
print('E:\Logs\Monitors\' + filename)
這可能是造成問題的原因,因為您實際上沒有加入子目錄。
這些可能會有所幫助;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.