Python3 獲取當前目錄下 所有文件的路徑


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')


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM