溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

python對(duì)文件目錄的操作方法實(shí)例總結(jié)

發(fā)布時(shí)間:2020-10-03 14:19:44 來源:腳本之家 閱讀:137 作者:輕舞肥羊 欄目:開發(fā)技術(shù)

本文實(shí)例講述了python對(duì)文件目錄的操作方法。分享給大家供大家參考,具體如下:

python 可以很方便的對(duì)文件進(jìn)行打開,讀寫操作,刪除操作,也可以很方便的對(duì)文件夾進(jìn)行遍歷操作??傮w說來,有如下幾個(gè)方面:

1. python 遍歷文件目錄,當(dāng)然可以遞歸
2. python 刪除文件
3. python 對(duì)文件進(jìn)行重命名操作
4. python 創(chuàng)建文件夾 (多個(gè)層級(jí)創(chuàng)建)
5. python 刪除文件夾  (多個(gè)層級(jí)刪除)
6. python 移動(dòng)文件
7. python 查找文件
8. 得到文件夾的大小

下面的代碼是我在用python 做一個(gè)網(wǎng)盤服務(wù)端的時(shí)候用到的一些方法,記錄下來,以供以后參考.

#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')

上面的代碼,根據(jù)方法的命名,就可以知道 python 操作文件以及文件夾的各種方法。

更多關(guān)于Python相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Python文件與目錄操作技巧匯總》、《Python文本文件操作技巧匯總》、《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python函數(shù)使用技巧總結(jié)》、《Python字符串操作技巧匯總》及《Python入門與進(jìn)階經(jīng)典教程》

希望本文所述對(duì)大家Python程序設(shè)計(jì)有所幫助。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI