python 读取文件夹以及文件夹下所有的文件名
import os LISTENER_DIR = os.getenv("LISTENER_DIR", "C:/Users/Sea/Desktop/Sea_Test/") def get_all_files(dir_path, fileList: list = []): listdir = os.listdir(dir_path) for file in listdir: if os.path.isdir(dir_path + file): get_all_files(dir_path + file + "/", fileList) else: fileList.append(dir_path + file) if __name__ == '__main__': files = [] get_all_files(LISTENER_DIR, files) print(files)
test:
['C:/Users/Sea/Desktop/Sea_Test/dsadsa/das.tmp', 'C:/Users/Sea/Desktop/Sea_Test/dsadsa/新建文件夹/新建 PPT 演示文稿.ppt', 'C:/Users/Sea/Desktop/Sea_Test/新建 PPT 演示文稿.ppt']
获取路径中的文件dir 和 文件名
方法一:split
s=r"C:\Users\Desktop\lesson\python\calss1.py"
s.split("\\")[-1] #输出为 class1.py
方法二:rfind
s=r"C:\Users\Desktop\lesson\python\calss1.py"
n=s.rfind("\\")#找到"\\"出现的位置
s[n+1:] #输出为 class1.py
s[:n] #输出为 'C:\\Users\\Desktop\\lesson\\python'
方法三:os.path.basename() (推荐)
s='C:/Users/Desktop/lesson/python/calss1.py'
import os
os.path.dirname(s) #输出为 'C:/Users/Desktop/lesson/python'
os.path.basename(s) #输出为 class1.py