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

yipeiwu_com4年前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 redis的连接及相关操作

redis简介 Redis是一个开源的使用ANSIC语言编写、支持网络、可基于内存亦可持久化的日志型、Key-Value数据库,并提供多种语言的API。是一个非关系型数据库,经常会用作缓...

Python+OpenCV感兴趣区域ROI提取方法

方法一:使用轮廓 步骤1 """src为原图""" ROI = np.zeros(src.shape, np.uint8) #感兴趣区域ROI proimage = src.co...

浅谈django2.0 ForeignKey参数的变化

Django2.0中编写models类下的ForeignKey book = models.ForeignKey('BookInfo') django2.0与之前的1.8不同,...

在python中利用numpy求解多项式以及多项式拟合的方法

构建一个二阶多项式:x^2 - 4x + 3 多项式求解 >>> p = np.poly1d([1,-4,3]) #二阶多项式系数 >>> p...

python实现矩阵打印

python实现矩阵打印

本文实例为大家分享了python实现矩阵打印的具体代码,供大家参考,具体内容如下 之前面试嵌入式软件的一道题,用c实现矩阵打印,考场上并没有写出来,之后总感觉自己写不出来也就没有去实现,...