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通过elixir包操作mysql数据库实例代码

python通过elixir包操作mysql数据库实例代码

本文研究的主要是python通过elixir包操作mysql数据库的相关实例,具体如下。 python操作数据库有很多方法,下面介绍elixir来操作数据库。elixir是对sqlalc...

Python3.5面向对象程序设计之类的继承和多态详解

Python3.5面向对象程序设计之类的继承和多态详解

本文实例讲述了Python3.5面向对象程序设计之类的继承和多态。分享给大家供大家参考,具体如下: 1、继承的定义 继承是指:可以使用现有类的所有功能,并在无需重新编写原来的类的情况下...

Python的socket模块源码中的一些实现要点分析

BaseServer 和 BaseRequestHandler Python为网络编程提高了更高级的封装。SocketServer.py 提供了不少网络服务的类。它们的设计很优雅。Pyt...

python结合API实现即时天气信息

python结合API实现即时天气信息

python结合API实现即时天气信息 import urllib.request import urllib.parse import json """ 利用“最美天气”抓取...

python cs架构实现简单文件传输

python cs架构实现简单文件传输

本文为大家分享了python cs架构实现简单文件的传输代码,供大家参考,具体内容如下 要实现简单文件的传输我们必须考虑这些问题: 1.什么是c/s架构? 顾名思义,就是客户端端/服务器...