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

yipeiwu_com6年前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 web中实现验证码图片代码分享

在Python web中实现验证码图片代码分享

系统版本: CentOS 7.4 Python版本: Python 3.6.1 在现在的WEB中,为了防止爬虫类程序提交表单,图片验证码是最常见也是最简单的应对方法之一。 1.验证码图...

django 中使用DateTime常用的时间查询方式

1、lt:小于 queryset=yourobject.objects .filter(时间字段名称__lt=start) 2、lte:小于等于 queryset=yourob...

OpenCV+face++实现实时人脸识别解锁功能

OpenCV+face++实现实时人脸识别解锁功能

本文实例为大家分享了OpenCV+face++实现实时人脸识别解锁功能的具体代码,供大家参考,具体内容如下 1.背景 最近做一个小东西,需要登录功能,一开始做的就是普通的密码登录功能,...

python采集百度百科的方法

本文实例讲述了python采集百度百科的方法。分享给大家供大家参考。具体如下: #!/usr/bin/python # -*- coding: utf-8 -*- #encoding...

Python3中正则模块re.compile、re.match及re.search函数用法详解

本文实例讲述了Python3中正则模块re.compile、re.match及re.search函数用法。分享给大家供大家参考,具体如下: re模块 re.compile、re.matc...