明霞山资源网 Design By www.htccd.com
os模块下有两个函数:
os.walk()
os.listdir()
# -*- 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) #当前路径下所有非目录子文件
输出格式为:
当前文件目录路径
当前路径下子文件目录(若存在, 不存在则为 [] )
当前路径下非目录子文件(仅为子文件的文件名)
子文件1路径
子文件1下的子文件目录
子文件1下的非目录子文件
子文件2路径
子文件2下的子文件目录
子文件2下的非目录子文件
# -*- coding: utf-8 -*-
import os
def file_name(file_dir):
L=[]
for root, dirs, files in os.walk(file_dir):
for file in files:
if os.path.splitext(file)[1] == '.jpeg':
L.append(os.path.join(root, file))
return L
#其中os.path.splitext()函数将路径拆分为文件名+扩展名
# -*- 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)
递归输出当前路径下所有非目录子文件
知识点补充:利用python获取当前目录名称和获取指定目录下的子目录和文件名称
import os
#获取当前目录名称
print(os.getcwd())
#获取指定目录下的子目录和文件名称
path = “D:\guaishounan”
print("【",path,"】 目录下包括的子目录和文件:")
for root,dirs,files in os.walk(path,topdown=True):
for name in dirs:
print(“子目录●”,os.path.join(root,name))
for name in files:
print(“文件◎”,os.path.join(root,name))
明霞山资源网 Design By www.htccd.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件! 如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件! 如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
明霞山资源网 Design By www.htccd.com
暂无评论...