相關(guān)模塊
- os
- os.path
- shutil
- pathlib(New in version 3.4)
基本操作
- 判斷文件(夾)是否存在。
os.path.exists(pathname)
# new
pathlib.Path(pathname).exists()
- 判斷路徑名是否為文件。
os.path.isfile(pathname)
# new
pathlib.Path(pathname).is_file()
- 判斷路徑名是否為目錄。
os.path.isdir(pathname)
# new
pathlib.Path(pathname).is_dir()
- 創(chuàng)建文件。
os.mknod(filename) # Windows下不可用
open(filename, "w") # 記得要關(guān)閉
# new
pathlib.Path(filename).touch(mode=438, exist_ok=True)
- 復(fù)制文件。
shutil.copyfile("oldfile", "newfile") # oldfile和newfile都只能是文件,目標文件會被覆蓋
shutil.copy("oldfile", "newfile") # oldfile只能是文件,newfile可以是文件,也可以是目標目錄
- 刪除文件。
os.remove(filename)
# new
pathlib.Path(pathname).unlink()
- 清空文件。
file = open("test.txt", w)
file.seek(0)
file.truncate() # 注意文件指針的位置
file.close()
- 創(chuàng)建目錄。
os.mkdir(pathname) # 創(chuàng)建單級目錄
# new
pathlib.Path(pathname).mkdir() # 創(chuàng)建單級目錄
os.makedirs(pathname) # 遞歸創(chuàng)建多級目錄
- 復(fù)制目錄。
# olddir 和 newdir 都只能是目錄,且 newdir 必須不存在
shutil.copytree("olddir", "newdir")
- 重命名文件或目錄。
os.rename(oldname, newname)
pathlib.Path(oldname).rename(newname)
- 移動文件或目錄
shutil.move(oldpath, newpath)
- 刪除目錄
os.rmdir("dir") #不能刪除非空目錄
# new
pathlib.Path("dir").rmdir()
# shutil.rmtree 可以刪除非空目錄,目錄打開時也能刪除
# 約等于'rd /Q /S dir'
shutil.rmtree("dir")
- 切換目錄
os.chdir(newpath)
- open 常用模式。
'r': 只讀(缺省。如果文件不存在,則拋出錯誤。)
'w': 只寫(如果文件不存在,則自動創(chuàng)建文件。)
'a': 追加
'r+': 讀寫
- 由全路徑名的到路徑和文件名
>>> pathfile = r'D:\abc\def\ghi.txt'
>>> os.path.dirname(pathfile)
'D:\\abc\\def'
# new
str(Path(pathfile).parent)
>>> os.path.basename(pathfile)
'ghi.txt'
# new
Path(pathfile).name
- 獲取文件大小
os.path.getsize(pathfile) #單位為字節(jié)(Byte)
# or
os.stat(pathfile).st_size
# new
pathlib.Path(pathfile).stat().st_size
- 獲取文件創(chuàng)建/修改/訪問時間。
os.path.getctime(pathfile) # 創(chuàng)建時間
os.path.getmtime(pathfile) # 修改時間
os.path.getatime(pathfile) # 訪問時間
# new
pathlib.Path(pathfile).stat().st_ctime # 創(chuàng)建時間
pathlib.Path(pathfile).stat().st_mtime # 修改時間
pathlib.Path(pathfile).stat().st_atime # 訪問時間
- 獲取當前文件目錄絕對路徑
os.path.abspath('.')
# new
str(pathlib.Path('.').resolve())
- 文件同步
fileObj.write(text)
fileObj.flush()
os.fsync(fileObj.fileno())
- 獲取文件擴展名
>>> os.path.splitext(r'D:\tmp\3.jpg')[1]
'.jpg'
>>> os.path.splitext('3.jpg')[1]
'.jpg'
# new
pathlib.Path(r'D:\tmp\3.jpg').suffix
本文出自 walker snapshot
更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯(lián)系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
