python對文件目錄的操作方法實例總結(jié)
本文實例講述了python對文件目錄的操作方法。分享給大家供大家參考,具體如下:
python 可以很方便的對文件進(jìn)行打開,讀寫操作,刪除操作,也可以很方便的對文件夾進(jìn)行遍歷操作??傮w說來,有如下幾個方面:
1. python 遍歷文件目錄,當(dāng)然可以遞歸
2. python 刪除文件
3. python 對文件進(jìn)行重命名操作
4. python 創(chuàng)建文件夾 (多個層級創(chuàng)建)
5. python 刪除文件夾 (多個層級刪除)
6. python 移動文件
7. python 查找文件
8. 得到文件夾的大小
下面的代碼是我在用python 做一個網(wǎng)盤服務(wù)端的時候用到的一些方法,記錄下來,以供以后參考.
#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)典教程》
希望本文所述對大家Python程序設(shè)計有所幫助。
相關(guān)文章
python+pytest接口自動化之日志管理模塊loguru簡介
python中有一個用起來非常簡便的第三方日志管理模塊--loguru,不僅可以避免logging的繁瑣配置,而且可以很簡單地避免在logging中多進(jìn)程多線程記錄日志時出現(xiàn)的問題,甚至還可以自定義控制臺輸出的日志顏色,接下來我們來學(xué)習(xí)怎么使用loguru模塊進(jìn)行日志管理2022-05-05
Python實戰(zhàn)之生成有關(guān)聯(lián)單選問卷
這篇文章主要為大家分享了一個Python實戰(zhàn)小案例——生成有關(guān)聯(lián)單選問卷,并且能根據(jù)問卷總分?jǐn)?shù)生成對應(yīng)判斷文案結(jié)果,感興趣的可以了解一下2023-04-04
pytorch之深度神經(jīng)網(wǎng)絡(luò)概念全面整理
這篇文章主要介紹了pytorch之深度神經(jīng)網(wǎng)絡(luò)概念,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-09-09
Python中g(shù)etpass模塊無回顯輸入源碼解析
這篇文章主要介紹了Python中g(shù)etpass模塊無回顯輸入源碼解析,具有一定借鑒價值,需要的朋友可以參考下2018-01-01
Python apscheduler實現(xiàn)定時任務(wù)的方法詳解
apscheduler(Advanced Python Scheduler)是一個用于Python的靈活、強(qiáng)大的定時任務(wù)調(diào)度庫,它允許您以各種方式安排函數(shù)或方法的執(zhí)行,下面就跟隨小編一起學(xué)習(xí)一下它的具體使用吧2023-10-10

