python对文件目录的操作方法实例总结


Posted in Python onJune 24, 2019

本文实例讲述了python对文件目录的操作方法。分享给大家供大家参考,具体如下:

python 可以很方便的对文件进行打开,读写操作,删除操作,也可以很方便的对文件夹进行遍历操作。总体说来,有如下几个方面:

1. python 遍历文件目录,当然可以递归
2. python 删除文件
3. python 对文件进行重命名操作
4. python 创建文件夹 (多个层级创建)
5. python 删除文件夹  (多个层级删除)
6. python 移动文件
7. python 查找文件
8. 得到文件夹的大小

下面的代码是我在用python 做一个网盘服务端的时候用到的一些方法,记录下来,以供以后参考.

#coding:utf-8
import StringIO
import json
import os
import time
import glob
import shutil
DATETIMEFORMATER='%Y-%m-%d %X'
#only for windows
RECYCLED_FOLDER_NAME='Recycled'
def dateformat(datetime):
  '''return GMT TIME,need to change to LOCAL TIME'''
  return time.strftime( DATETIMEFORMATER,time.gmtime(datetime) )
def filesizeformat(size):
  ''' Convert file size to string '''
  KBSIZE=1024.00
  strSize='0 Byte'
  if (size < KBSIZE):
    strSize = '%.2f Byte' % (size)
  elif (size >= KBSIZE and size < KBSIZE**2):
    strSize = '%.2f K' % (size / KBSIZE)
  elif (size >= KBSIZE**2 and size < KBSIZE**3):
    strSize = '%.2f M' % (size / KBSIZE / KBSIZE)
  elif (size >= KBSIZE**3):
    strSize = '%.2f G' % (size / KBSIZE / KBSIZE / KBSIZE)
  return strSize
def listdir(path):
  if os.path.isfile(path):
    return '[]'
  allFiles=os.listdir(path)
  retlist=[]
  for cfile in allFiles:
    fileinfo={}
    filepath=(path+os.path.sep+cfile).replace("\\","/")
    if cfile==RECYCLED_FOLDER_NAME:
      continue
    if os.path.isdir(filepath):
      fileinfo['isfile'] = '0'
      fileinfo['size'] = getfoldersize(filepath)
    else:
      fileinfo['isfile'] = '1'
      fileinfo['size'] = os.path.getsize(filepath)
    fileinfo['name'] = cfile
    fileinfo['lastvisittime'] = dateformat( os.path.getatime(filepath) )
    fileinfo['createtime'] = dateformat( os.path.getctime(filepath) )
    fileinfo['lastmodifytime'] = dateformat( os.path.getmtime(filepath) )
    retlist.append(fileinfo)
  retStr=json.dumps(retlist,encoding='utf-8')
  return retStr
def deletefile(path):
  if os.path.exists(path):
    os.remove(path)
def rename(old,new):
  if os.path.exists(old):
    os.rename(old, new)
def checkoutfile(path):
  pass
def checkinfile(path):
  pass
def lockfile(path):
  pass
def unlockfile(path):
  pass
def createfolder(path):
  if not os.path.exists(path):
    os.mkdir(path)
def createfolders(path):
  if not os.path.exists(path):
    os.makedirs(path);
def deletefolder(path):
  if os.path.isdir(path):
    os.rmdir(path)
def retreeExceptionHandler(fun,path,excinfo):
  pass
def deletefolders(path):
#  if os.path.isdir(path):
#    os.removedirs(path)
  shutil.rmtree(path,ignore_errors=False,onerror=retreeExceptionHandler)
def movefile(old,new):
  shutil.move(old, new)
def getfoldersize(path):
  size = 0
  for root, dirs, files in os.walk(path):
    size += sum([os.path.getsize(os.path.join(root, name)) for name in files])
  return size
def searchfile(path,ext):
  returnList=glob.glob1(path, ext)
  return returnList
if __name__=='__main__':
  listdir('c:/vDriver')
  #searchfile('c:/vDriver','*.log')

上面的代码,根据方法的命名,就可以知道 python 操作文件以及文件夹的各种方法。

希望本文所述对大家Python程序设计有所帮助。

Python 相关文章推荐
python调用java的Webservice示例
Mar 10 Python
用Python编写脚本使IE实现代理上网的教程
Apr 23 Python
Python编程中运用闭包时所需要注意的一些地方
May 02 Python
python写日志封装类实例
Jun 28 Python
Python给你的头像加上圣诞帽
Jan 04 Python
神经网络(BP)算法Python实现及应用
Apr 16 Python
Python实现基于PIL和tesseract的验证码识别功能示例
Jul 11 Python
在django admin中添加自定义视图的例子
Jul 26 Python
Python爬虫:url中带字典列表参数的编码转换方法
Aug 21 Python
python的等深分箱实例
Nov 22 Python
python与js主要区别点总结
Sep 13 Python
Python实现天气查询软件
Jun 07 Python
详解10个可以快速用Python进行数据分析的小技巧
Jun 24 #Python
python跳出双层for循环的解决方法
Jun 24 #Python
解决python xx.py文件点击完之后一闪而过的问题
Jun 24 #Python
解决python执行不输出系统命令弹框的问题
Jun 24 #Python
python实现在cmd窗口显示彩色文字
Jun 24 #Python
打包python 加icon 去掉cmd黑窗口方法
Jun 24 #Python
python隐藏终端执行cmd命令的方法
Jun 24 #Python
You might like
PHP有序表查找之二分查找(折半查找)算法示例
2018/02/09 PHP
Yii框架函数简单用法分析
2019/09/09 PHP
node.js适合游戏后台开发吗?
2014/09/03 Javascript
微信小程序 Image API实例详解
2016/09/30 Javascript
纯JS代码实现隔行变色鼠标移入高亮
2016/11/23 Javascript
谈谈第三方App接入微信登录 解读
2016/12/27 Javascript
jQuery+HTML5实现弹出创意搜索框层
2016/12/29 Javascript
Angularjs处理页面闪烁的解决方法
2017/03/09 Javascript
详解小程序缓存插件(mrc)
2018/08/17 Javascript
Python实现的简单万年历例子分享
2014/04/25 Python
Python字符和字符值(ASCII或Unicode码值)转换方法
2015/05/21 Python
Python中的super()方法使用简介
2015/08/14 Python
Python探索之ModelForm代码详解
2017/10/26 Python
pandas每次多Sheet写入文件的方法
2018/12/10 Python
对python中的控制条件、循环和跳出详解
2019/06/24 Python
python爬虫的一个常见简单js反爬详解
2019/07/09 Python
python爬虫 execjs安装配置及使用
2019/07/30 Python
python垃圾回收机制(GC)原理解析
2019/12/30 Python
jupyter lab文件导出/下载方式
2020/04/22 Python
卡西欧B级产品官方网站:Casio Outlet
2018/05/22 全球购物
印尼第一大家居、生活和家具电子商务:Ruparupa
2019/11/25 全球购物
构造方法和其他方法的区别?怎么调用父类的构造方法
2013/09/22 面试题
HttpServlet类中的主要方法都有哪些?各自的作用是什么?
2014/03/16 面试题
四种会话跟踪技术
2015/05/20 面试题
综合办公室个人的自我评价
2013/12/22 职场文书
企业安全生产责任书
2014/04/14 职场文书
2014年党的群众路线教育实践活动总结
2014/04/25 职场文书
电气自动化求职信
2014/06/24 职场文书
2014年质检员工作总结
2014/11/18 职场文书
2014年乡镇工会工作总结
2014/12/02 职场文书
优秀党务工作者先进事迹材料
2014/12/25 职场文书
2015高三毕业寄语赠言
2015/02/27 职场文书
2015年安全教育月活动总结
2015/03/26 职场文书
2015年乡镇残联工作总结
2015/05/13 职场文书
SQL Server表分区删除详情
2021/10/16 SQL Server
Java Lambda表达式常用的函数式接口
2022/04/07 Java/Android