python對文件目錄的操作方法實(shí)例總結(jié)
本文實(shí)例講述了python對文件目錄的操作方法。分享給大家供大家參考,具體如下:
python 可以很方便的對文件進(jìn)行打開,讀寫操作,刪除操作,也可以很方便的對文件夾進(jìn)行遍歷操作??傮w說來,有如下幾個(gè)方面:
1. python 遍歷文件目錄,當(dāng)然可以遞歸
2. python 刪除文件
3. python 對文件進(jìn)行重命名操作
4. python 創(chuàng)建文件夾 (多個(gè)層級創(chuàng)建)
5. python 刪除文件夾 (多個(gè)層級刪除)
6. python 移動文件
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)典教程》
希望本文所述對大家Python程序設(shè)計(jì)有所幫助。
相關(guān)文章
ubuntu 18.04搭建python環(huán)境(pycharm+anaconda)
這篇文章主要為大家詳細(xì)介紹了ubuntu 18.04搭建python環(huán)境,包括Anaconda安裝、Pycharm安裝及初始配置,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2019-06-06
Python報(bào)錯(cuò):OSError:?[Errno?22]?Invalid?argument解決方案及應(yīng)用實(shí)例
最近跑別人的項(xiàng)目遇到一個(gè)這樣的問題一開始以為是沒有用管理員的權(quán)限運(yùn)行,導(dǎo)致創(chuàng)建不了日志文件后來發(fā)現(xiàn)是和windows的命名規(guī)則沖突了,這篇文章主要給大家介紹了關(guān)于Python報(bào)錯(cuò):OSError:?[Errno?22]?Invalid?argument的解決方案及應(yīng)用實(shí)例,需要的朋友可以參考下2024-07-07
Python?PyCharm無法打開終端命令行最終解決方案(實(shí)測成功)
這篇文章主要介紹了在使用PyCharm?2024版本時(shí)遇到的無法打開終端的問題,文中提供了兩種解決方案,大家可以根據(jù)自己的需求選擇對應(yīng)的解決方法,需要的朋友可以參考下2024-12-12
jupyter運(yùn)行時(shí)左邊一直出現(xiàn)*號問題及解決
這篇文章主要介紹了jupyter運(yùn)行時(shí)左邊一直出現(xiàn)*號問題及解決方案,具有很好的參考價(jià)值,希望對大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-09-09
Requests庫實(shí)現(xiàn)數(shù)據(jù)抓取與處理功能
本文介紹了Python中常用的第三方庫Requests的基本用法和高級功能,我們學(xué)習(xí)了如何發(fā)起HTTP請求、處理響應(yīng)、使用會話對象、設(shè)置代理和證書驗(yàn)證等技巧,需要的朋友可以參考下2023-05-05

