目录
代码四:依次从内层到外层获取当前路径下文件(改造自代码三),也可直接代码一获取
代码五:获取当前路径下一层指定后缀文件列表(多层可改造代码三)
代码一: 输出文件目录相关内容
os.walk(file_dir)从外到内获取多层
# -*- coding: utf-8 -*-
import os
def file_name(file_dir):
for root, dirs, files in os.walk(file_dir):
print(root) #当前目录路径
print(dirs) #当前路径下所有子目录
print(files) #当前路径下所有非目录子文件
代码一会从外到内,将文件夹三个内容一层一层的输出。
代码二:输出一个目录下所有文件名字(第一层)
os.listdir(rootdir) 当前层
os.path.isfile(list[i]):#判断是否是文件
#获取一个路径下第一层,所有文件名列表
def get_filenames(file_dir):
L=[]
list = os.listdir(rootdir) #列出文件夹下所有的目录与文件
for i in range(0,len(list)):
if os.path.isfile(list[i]):#判断是否是文件
L.append(os.path.join(file_dir,list[i]))
代码三:返回当前路径下所有层的文件路径列表
os.path.isdir(file_path)判断是否是目录(文件夹)
# -*- coding: utf-8 -*-
import os
def listdir(path, list_name): #传入存储的list
for file in os.listdir(path):
file_path = os.path.join(path, file)
if os.path.isdir(file_path):
listdir(file_path, list_name)
else:
list_name.append(file_path)
print(list_name)#虽然打印出来,但是最后的打印才是return的最后结果
return list_name
list_name=[] #需要在外层定义,才能获取当前路径所有文件名,试想在内层定义会如何
list_name=listdir(rootdir, list_name)#返回当前路径下所有文件路径列表
#['E:\\Mypython3\\wenshu_my\\data_my\\fen_200\\10_fact.txt', 'E:\\Mypython3\\wenshu_my\\data_my\\fen_200\\11_fact.txt', 'E:\\Mypython3\\wenshu_my\\data_my\\fen_200\\12_fact.txt', 'E:\\Mypython3\\wenshu_my\\data_my\\fen_200\\13_fact.txt', 'E:\\Mypython3\\wenshu_my\\data_my\\fen_200\\14_fact.txt', 'E:\\Mypython3\\wenshu_my\\data_my\\fen_200\\15_fact.txt', 'E:\\Mypython3\\wenshu_my\\data_my\\fen_200\\16_fact.txt', 'E:\\Mypython3\\wenshu_my\\data_my\\fen_200\\17_fact.txt', 'E:\\Mypython3\\wenshu_my\\data_my\\fen_200\\18_fact.txt', 'E:\\Mypython3\\wenshu_my\\data_my\\fen_200\\19_fact.txt', 'E:\\Mypython3\\wenshu_my\\data_my\\fen_200\\1_24\\10_fact.txt', 'E:\\Mypython3\\wenshu_my\\data_my\\fen_200\\1_24\\11_fact.txt', 'E:\\Mypython3\\wenshu_my\\data_my\\fen_200\\1_24\\12_fact.txt', 'E:\\Mypython3\\wenshu_my\\data_my\\fen_200\\1_24\\13_fact.txt', 'E:\\Mypython3\\wenshu_my\\data_my\\fen_200\\1_24\\14_fact.txt', 'E:\\Mypython3\\wenshu_my\\data_my\\fen_200\\1_24\\15_fact.txt', 'E:\\Mypython3\\wenshu_my\\data_my\\fen_200\\1_24\\16_fact.txt', 'E:\\Mypython3\\wenshu_my\\data_my\\fen_200\\1_24\\17_fact.txt', 'E:\\Mypython3\\wenshu_my\\data_my\\fen_200\\1_24\\18_fact.txt', 'E:\\Mypython3\\wenshu_my\\data_my\\fen_200\\1_24\\19_fact.txt', 'E:\\Mypython3\\wenshu_my\\data_my\\fen_200\\1_24\\1_fact.txt', 'E:\\Mypython3\\wenshu_my\\data_my\\fen_200\\1_24\\20_fact.txt', 'E:\\Mypython3\\wenshu_my\\data_my\\fen_200\\1_24\\21_fact.txt', 'E:\\Mypython3\\wenshu_my\\data_my\\fen_200\\1_24\\22_fact.txt', 'E:\\Mypython3\\wenshu_my\\data_my\\fen_200\\1_24\\24_fact.txt', 'E:\\Mypython3\\wenshu_my\\data_my\\fen_200\\1_24\\2_fact.txt', 'E:\\Mypython3\\wenshu_my\\data_my\\fen_200\\1_24\\3_fact.txt', 'E:\\Mypython3\\