本文实例讲述了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文本文件操作技巧汇总》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》及《Python入门与进阶经典教程》

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

标签:
python,文件目录,操作方法

免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件! 如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
评论“python对文件目录的操作方法实例总结”
暂无“python对文件目录的操作方法实例总结”评论...

《魔兽世界》大逃杀!60人新游玩模式《强袭风暴》3月21日上线

暴雪近日发布了《魔兽世界》10.2.6 更新内容,新游玩模式《强袭风暴》即将于3月21 日在亚服上线,届时玩家将前往阿拉希高地展开一场 60 人大逃杀对战。

艾泽拉斯的冒险者已经征服了艾泽拉斯的大地及遥远的彼岸。他们在对抗世界上最致命的敌人时展现出过人的手腕,并且成功阻止终结宇宙等级的威胁。当他们在为即将于《魔兽世界》资料片《地心之战》中来袭的萨拉塔斯势力做战斗准备时,他们还需要在熟悉的阿拉希高地面对一个全新的敌人──那就是彼此。在《巨龙崛起》10.2.6 更新的《强袭风暴》中,玩家将会进入一个全新的海盗主题大逃杀式限时活动,其中包含极高的风险和史诗级的奖励。

《强袭风暴》不是普通的战场,作为一个独立于主游戏之外的活动,玩家可以用大逃杀的风格来体验《魔兽世界》,不分职业、不分装备(除了你在赛局中捡到的),光是技巧和战略的强弱之分就能决定出谁才是能坚持到最后的赢家。本次活动将会开放单人和双人模式,玩家在加入海盗主题的预赛大厅区域前,可以从强袭风暴角色画面新增好友。游玩游戏将可以累计名望轨迹,《巨龙崛起》和《魔兽世界:巫妖王之怒 经典版》的玩家都可以获得奖励。