Python 获取指定文件夹下的目录和文件的实现
作者:AlanWang4523 时间:2023-12-23 22:44:29
经常有需要扫描目录,对文件做批量处理的需求,所以对目录处理这块做了下学习和总结。Python 中扫描目录有两种方法:os.listdir 和 os.walk。
一、os.listdir 方法
os.listdir() 方法用于返回指定的目录下包含的文件或子目录的名字的列表。这个列表以字母顺序。其得到的是仅当前路径下的文件名,不包括子目录中的文件,如果需要得到所有文件需要递归。 它也不包括 '.' 和 '..' 即使它在目录中。
语法格式如下:
os.listdir(path)
实例代码
def list_dir(file_dir):
'''
通过 listdir 得到的是仅当前路径下的文件名,不包括子目录中的文件,如果需要得到所有文件需要递归
'''
print'\n\n<><><><><><> listdir <><><><><><>'
print "current dir : {0}".format(file_dir)
dir_list = os.listdir(file_dir)
for cur_file in dir_list:
# 获取文件的绝对路径
path = os.path.join(file_dir, cur_file)
if os.path.isfile(path): # 判断是否是文件还是目录需要用绝对路径
print "{0} : is file!".format(cur_file)
if os.path.isdir(path):
print "{0} : is dir!".format(cur_file)
list_dir(path) # 递归子目录
二、os.walk 方法
os.walk() 方法用于通过在目录树中游走输出在目录中的文件名,向上或者向下。是一个简单易用的文件、目录遍历器,可以帮助我们高效的处理文件、目录方面的事情。
语法格式如下:
os.walk(top[, topdown=True[, onerror=None[, followlinks=False]]])
方法参数说明:
top:要遍历的目录的路径
topdown:可选,如果为 True,则优先遍历 top 目录,以及 top 目录下的每一个子目录,否则优先遍历 top 的子目录,默认为 True
onerror: 可选, 需要一个 callable 对象,当 walk 异常时调用
followlinks:可选, 如果为 True,则会遍历目录下的快捷方式(linux 下是 symbolic link)实际所指的目录,默认为 False
args:包含那些没有 '-' 或 '--' 的参数列表
返回值: 三元组 (root, dirs, files)
root :所指的是当前正在遍历的目录的地址
dirs :当前文件夹中所有目录名字的 list (不包括子目录)
files :当前文件夹中所有的文件 (不包括子目录中的文件)
实例
def work_dir(file_dir):
print'\n\n<><><><><> work dir <><><><><>'
for root, dirs, files in os.walk(file_dir):
print'\n========================================'
print "root : {0}".format(root)
print "dirs : {0}".format(dirs)
print "files : {0}".format(files)
for file in files:
try:
print'-----------------------------------'
file_name = os.path.splitext(file)[0]
file_suffix = os.path.splitext(file)[1]
file_path = os.path.join(root, file)
file_abs_path = os.path.abspath(file)
file_parent = os.path.dirname(file_path)
print "file : {0}".format(file)
print "file_name : {0}".format(file_name)
print "file_suffix : {0}".format(file_suffix)
print "file_path : {0}".format(file_path)
print "file_abs_path : {0}".format(file_abs_path)
print "file_parent : {0}".format(file_parent)
except Exception, e:
print "Exception", e
三、其他跟文件相关的常用方法
os.path.splitext():分离文件名和扩展名
file = "file_test.txt"
file_name = os.path.splitext(file)[0] # 输出:file_test
file_suffix = os.path.splitext(file)[1] # 输出:.txt
os.path.exists():判断文件或目录是否存在
os.path.isfile():判断是否是文件
os.path.isdir():判断是否是目录
os.path.dirname():获取当前文件所在的目录,即父目录
os.makedirs():创建多级目录
os.mkdir():创建单级目录
os.path.getsize():获取文件大小
来源:https://blog.csdn.net/u011520181/article/details/80866790
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
详解MySQL双活同步复制四种解决方案
![](https://img.aspxhome.com/file/2023/7/106607_0s.jpg)
Python中使用第三方库xlrd来读取Excel示例
Javascript操作cookie的类
PHP使用CURL实现多线程抓取网页
ASP中Utf-8与Gb2312编码转换乱码问题的解决方法 页面编码声明
注册表单的规则——读《Patterns for Sign Up &Ramp Up》
简单聊聊Python中的鸭子类型和猴子补丁
python远程登录代码
最新PyCharm从安装到PyCharm永久激活再到PyCharm官方中文汉化详细教程
![](https://img.aspxhome.com/file/2023/0/82940_0s.png)
Python Web框架之Django框架cookie和session用法分析
详解Python中range()与xrange()的区别
使用python处理题库表格并转化为word形式的实现
![](https://img.aspxhome.com/file/2023/5/61175_0s.jpg)
教你利用Python破解ZIP或RAR文件密码
python matplotlib实现将图例放在图外
![](https://img.aspxhome.com/file/2023/2/85122_0s.jpg)
GO语言包管理工具go mod以及包详解
![](https://img.aspxhome.com/file/2023/7/127377_0s.jpg)
Python和perl实现批量对目录下电子书文件重命名的代码分享
python数字图像处理之高级滤波代码详解
![](https://img.aspxhome.com/file/2023/6/133406_0s.jpg)
SQL 分布式查询、插入递增列示例
python中的os.mkdir和os.makedirs的使用区别及如何查看某个模块中的某些字母开头的属性方法
通过实例解析js简易模块加载器
![](https://img.aspxhome.com/file/2023/6/136736_0s.png)