日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

python类库31[文件和目录os+os.path+shutil]

發布時間:2023/12/10 python 26 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python类库31[文件和目录os+os.path+shutil] 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.


一 常用函數

os模塊

os.sep 表示默認的文件路徑分隔符,windows為\, linux為/
os.walk(spath): 用來遍歷目錄下的文件和子目錄
os.listdir(dirname):列出dirname下的目錄和文件
os.mkdir() : 創建目錄
os.makedirs(): 創建目錄,包含中間級目錄
os.remove():刪除文件,不能是目錄
os.rmdir():刪除空目錄
os.removedirs(path):刪除目錄及其子目錄
os.rename(src, dst) :修改文件名
os.renames(old, new) :修改文件或目錄名,包含中間級

os.chdir("/tmp") : 更改當前目錄
os.chmod( "c:\\test\\buildid.txt", stat.S_IWRITE ) : 去除文件的只讀屬性

os.path模塊

os.path.pathsep 表示默認的路徑間的分隔符,windows為; Linux為:
os.path.isdir(name):判斷name是不是一個目錄,name不是目錄就返回false
os.path.isfile(name):判斷name是不是一個文件,不存在name也返回false
os.path.exists(name):判斷是否存在文件或目錄name
os.path.getsize(name):獲得文件大小,如果name是目錄返回0L
os.path.getctime(name):獲得文件的創建時間

os.path.getmtime(name):獲得文件的修改時間

os.path.getatime(name):獲得文件的最后訪問時間

?

os.path.isabs(name):測試是否是絕對路徑
os.path.abspath(name):獲得絕對路徑
os.path.normpath(path):規范path字符串形式

os.path.relpath(path, start='.'):返回路徑的相對版本

os.path.split(name):分割文件名與目錄(事實上,如果你完全使用目錄,它也會將最后一個目錄作為文件名而分離,同時它不會判斷文件或目錄是否存在)
os.path.splitext():分離文件名與擴展名
os.path.splitdrive():分離驅動名或unc名字
os.path.join(path,name):連接目錄與文件名或目錄

os.path.basename(path):返回文件名
os.path.dirname(path):返回文件路徑

os.path.expanduser("~"):用來獲得user的home路徑。

shutil模塊
shutil.copyfile(src, dst): 拷貝文件
shutil.copytree(srcDir, dstDir) : 拷貝目錄

?

shutil.rmtree('dir') : 刪除非空文件夾

shutil.move('old','new') :修改文件和目錄名稱

?

glob模塊

匹配文件:glob.glob(r”c:\linuxany\*.py”)
?

二 實例 (os.walk的遍歷過程如下)



import?os

#?tree?c:\test?/f
#
C:\TEST
#
│??test.log
#

#
├─test2
#
│??????test2.log
#

#
└─test3

tree?
=?os.walk('C:/test')
for?directoryItem?in?tree:
????directory
=directoryItem[0]
????subDirectories
=directoryItem[1]
????filesInDirectory
=directoryItem[2]????
????
print('-----------------')
????
print('the?directory?is?:',?directory)
????
print('the?sub?directories?are?:?',?subDirectories)
????
print('the?files?are?:',?filesInDirectory)

#-----------------
#
the?directory?is?:?C:/test
#
the?sub?directories?are?:??['test2',?'test3']
#
the?files?are?:?['test.log']
#
-----------------
#
the?directory?is?:?C:/test\test2
#
the?sub?directories?are?:??[]
#
the?files?are?:?['test2.log']
#
-----------------
#
the?directory?is?:?C:/test\test3
#
the?sub?directories?are?:??[]
#
the?files?are?:?[]


完!

?

轉載于:https://www.cnblogs.com/itech/archive/2009/12/16/1625636.html

創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎

總結

以上是生活随笔為你收集整理的python类库31[文件和目录os+os.path+shutil]的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。