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

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程语言 > python >内容正文

python

Python模块: 文件和目录os+shutil

發(fā)布時間:2023/12/15 python 28 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Python模块: 文件和目录os+shutil 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

一 常用函數(shù)

os模塊

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

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

os.path模塊

os.path.pathsep 表示默認(rèn)的路徑間的分隔符,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):獲得文件的創(chuàng)建時間

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

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

?

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

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

os.path.split(name):分割文件名與目錄(事實上,如果你完全使用目錄,它也會將最后一個目錄作為文件名而分離,同時它不會判斷文件或目錄是否存在)
os.path.splitext():分離文件名與擴(kuò)展名
os.path.splitdrive():分離驅(qū)動名或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的遍歷過程如下)

1 Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/--> 2 3 import os 4 5 # tree c:\test /f 6 #C:\TEST 7 #│ test.log 8 # 9 #├─test2 10 #│ test2.log 11 # 12 #└─test3 13 14 tree = os.walk('C:/test') 15 for directoryItem in tree: 16 directory=directoryItem[0] 17 subDirectories=directoryItem[1] 18 filesInDirectory=directoryItem[2] 19 print('-----------------') 20 print('the directory is :', directory) 21 print('the sub directories are : ', subDirectories) 22 print('the files are :', filesInDirectory) 23 24 #----------------- 25 #the directory is : C:/test 26 #the sub directories are : ['test2', 'test3'] 27 #the files are : ['test.log'] 28 #----------------- 29 #the directory is : C:/test\test2 30 #the sub directories are : [] 31 #the files are : ['test2.log'] 32 #----------------- 33 #the directory is : C:/test\test3 34 #the sub directories are : [] 35 #the files are : []

轉(zhuǎn):http://www.cnblogs.com/itech/archive/2009/12/16/1625636.html

總結(jié)

以上是生活随笔為你收集整理的Python模块: 文件和目录os+shutil的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。