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中atexit模块的基本使用示例

Python中atexit模块的基本使用示例

atexit模块很简单,只定义了一个register函数用于注册程序退出时的回调函数,我们可以在这个回调函数中做一些资源清理的操作。 注:如果程序是非正常crash,或者通过os._ex...

Python 静态方法和类方法实例分析

Python 静态方法和类方法实例分析

本文实例讲述了Python 静态方法和类方法。分享给大家供大家参考,具体如下: 1. 类属性、实例属性 它们在定义和使用中有所区别,而最本质的区别是内存中保存的位置不同, 实例属性属于对...

研究Python的ORM框架中的SQLAlchemy库的映射关系

前面介绍了关于用户账户的User表,但是现实生活中随着问题的复杂化数据库存储的数据不可能这么简单,让我们设想有另外一张表,这张表和User有联系,也能够被映射和查询,那么这张表可以存储关...

Python安装Imaging报错:The _imaging C module is not installed问题解决方法

今天写Python程序上传图片需要用到PIL库,于是到http://www.pythonware.com/products/pil/#pil117下载了一个1.1.7版本的,我用的是Ce...

windows下cx_Freeze生成Python可执行程序的详细步骤

windows下cx_Freeze生成Python可执行程序的详细步骤

目前网上能获取的免费的python打包工具主要有三种:py2exe、PyInstaller和cx_Freeze。 下面简单介绍windows7下cx_Freeze打包python生成可执...