Python遍历指定文件及文件夹的方法

yipeiwu_com5年前Python基础

本文实例讲述了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走迷宫算法题

一道python走迷宫算法题

前几天逛博客时看到了这样一道问题,感觉比较有趣,就自己思考了下方案顺便用python实现了一下。题目如下: 用一个二维数组表示一个简单的迷宫,用0表示通路,用1表示阻断,老鼠在每个点上可...

使用PYTHON解析Wireshark的PCAP文件方法

PYTHON首先要安装scapy模块 PY3的安装scapy-python3,使用PIP安装就好了,注意,PY3无法使用pyinstaller打包文件,PY2正常 PY2的安装scapy...

Python之os操作方法(详解)

1. os.path.driname(path):返回路径的上一级路径字符串。   >>> os.path.dirname('D:\Games')   'D:\\'...

Python实现PyPDF2处理PDF文件的方法示例

Python实现PyPDF2处理PDF文件的方法示例

实际应用中,可能会涉及处理 pdf 文件,PyPDF2 就是这样一个库,使用它可以轻松的处理 pdf 文件,它提供了读,割,合并,文件转换等多种操作。 文档地址:http://pytho...

python sorted方法和列表使用解析

python sorted方法和列表使用解析

这篇文章主要介绍了python sorted方法和列表使用解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 一、基本形式列表有自己的...