Python遍历指定文件及文件夹的方法
作者:小五义 时间:2023-04-07 23:10:17
本文实例讲述了Python遍历指定文件及文件夹的方法。分享给大家供大家参考。具体如下:
初次编写:
import os
def searchdir(arg,dirname,names):
for filespath in names:
open ('c:\\test.txt','a').write('%s\r\n'%(os.path.join(dirname,filespath)))
if __name__=="__main__":
paths="g:\\"
os.path.walk(paths,searchdir,())
做了修改,添加了文件属性
# -*- coding: cp936 -*-
import os,time
#将文件属性中的时间改为‘2011-1-12 00:00:00格式'
def formattime(localtime):
endtime=time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(localtime))
return endtime
def searchdir(arg,dirname,names):
for filespath in names:
#得到文件路径
fullpath=os.path.join(dirname,filespath)
#得到文件属性
statinfo=os.stat(fullpath)
#文件大小
sizefile=statinfo.st_size
#创建时间
creattime=formattime(statinfo.st_ctime)
#修改时间
maketime=formattime(statinfo.st_mtime)
#浏览时间
readtime=formattime(statinfo.st_atime)
#判断是文件夹还是文件
if os.path.isdir(fullpath):
filestat='DIR'
else:
filestat='FILE'
open ('c:\\test.txt','a').write('【%s】路径:%s 文件大小(B):%s 创建时间:%s 修改时间:%s 浏览时间:%s\r\n'%(filestat,fullpath,sizefile,creattime,maketime,readtime))
if __name__=="__main__":
paths="g:\\"
os.path.walk(paths,searchdir,())
希望本文所述对大家的Python程序设计有所帮助。
标签:Python,遍历,文件
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
python中matplotlib实现最小二乘法拟合的过程详解
2022-03-07 05:17:51
![](https://img.aspxhome.com/file/2023/8/92078_0s.png)
codeigniter发送邮件并打印调试信息的方法
2024-05-13 09:57:03
远程登录MySQL服务(小白入门篇)
2024-01-19 09:02:56
Django实现简单的分页功能
2021-08-08 20:53:14
![](https://img.aspxhome.com/file/2023/9/72109_0s.jpg)
Go秒爬博客园100页新闻
2024-04-26 17:15:49
Python 面向对象静态方法、类方法、属性方法知识点小结
2022-02-10 07:45:52
python 日志模块 日志等级设置失效的解决方案
2022-01-25 07:27:19
JSP实现浏览器关闭cookies情况下的会话管理
2024-03-27 07:29:10
Python pyecharts模块安装与入门教程
2023-09-11 06:52:41
![](https://img.aspxhome.com/file/2023/3/118653_0s.png)
oracle调试存储过程的过程详解
2024-01-13 03:51:17
![](https://img.aspxhome.com/file/2023/8/64098_0s.png)
详解Python中with语句的用法
2022-07-31 05:24:52
超全MySQL学习笔记
2024-01-25 20:21:45
![](https://img.aspxhome.com/file/2023/1/112351_0s.jpg)
Python 3行代码提取音乐高潮部分
2021-11-14 13:15:54
![](https://img.aspxhome.com/file/2023/6/80606_0s.png)
Python中常用操作字符串的函数与方法总结
2023-07-25 12:09:23
JS通过FSO将unicode字符写入文本
2009-06-01 12:26:00
JS 实现请求调度器
2024-04-22 22:37:24
![](https://img.aspxhome.com/file/2023/8/135608_0s.png)
Python中使用不同编码读写txt文件详解
2023-06-29 20:35:27
关系型数据库与非关系型数据库简介
2024-01-19 05:36:44
![](https://img.aspxhome.com/file/2023/5/92785_0s.png)
Python实现连点器的示例代码
2023-04-17 00:11:29
![](https://img.aspxhome.com/file/2023/8/124138_0s.png)
ASP使用连接MYSQL数据库全攻略
2007-09-23 09:06:00