import os
def all_files_path(rootDir):
for root, dirs, files in os.walk(rootDir): # 分別代表根目錄、文件夾、文件
for file in files: # 遍歷文件
file_path = os.path.join(root, file) # 獲取文件絕對路徑
filepaths.append(file_path) # 將文件路徑添加進列表
for dir in dirs: # 遍歷目錄下的子目錄
dir_path = os.path.join(root,dir) # 獲取子目錄路徑
all_files_path(dir_path) # 遞歸調用
if __name__ == "__main__":
filepaths = []
all_files_path(os.getcwd()) #獲取當前目錄
#all_files_path("dirpath")手動替換目錄
with open('dir.txt', 'w') as f:
for filepath in filepaths:
f.write(filepath + '\n')
測試發現因為路徑的遍歷會存在重復。只想要文件直接
import os
def all_files_path(rootDir):
for root, dirs, files in os.walk(rootDir): # 分別代表根目錄、文件夾、文件
for file in files: # 遍歷文件
file_path = os.path.join(root, file) # 獲取文件絕對路徑
filepaths.append(file_path) # 將文件路徑添加進列表
if __name__ == "__main__":
filepaths = []
all_files_path(os.getcwd()) #獲取當前目錄
#all_files_path("dirpath")手動替換目錄
with open('dir.txt', 'w') as f:
for filepath in filepaths:
f.write(filepath + '\n')