Python檔案與檔案夾常見基本操作總結,
本文執行個體講述了Python檔案與檔案夾常見基本操作。分享給大家供大家參考,具體如下:
1、判斷檔案(夾)是否存在。
os.path.exists(pathname)
2、判斷路徑名是否為檔案。
os.path.isfile(pathname)
3、判斷路徑名是否為目錄。
os.path.isdir(pathname)
4、建立檔案。
os.mknod(filename) #windows下不可用open(filename, "w") #記得要關閉
5、複製檔案。
shutil.copyfile("oldfile", "newfile") #oldfile和newfile都只能是檔案shutil.copy("oldfile", "newfile") #oldfile只能是檔案,newfile可以是檔案,也可以是目標目錄
6、刪除檔案。
os.remove(filename)
7、清空檔案。
file = open("test.txt", w)file.seek(0)file.truncate() #注意檔案指標的位置file.close()
8、建立目錄。
os.mkdir(pathname) #建立單級目錄os.makedirs(pathname) #遞迴建立多級目錄
9、複製目錄。
shutil.copytree("olddir", "newdir")#olddir和newdir都只能是目錄,且newdir必須不存在
10、重新命名檔案或目錄。
os.rename(oldname, newname)
11、移動檔案或目錄。
shutil.move(oldpath, newpath)
12、刪除目錄。
os.rmdir("dir") #不能刪除非空目錄'''#可以刪除非空目錄,目錄開啟時也能刪除#約等於'rd /Q /S dir''''shutil.rmtree("dir")
12.1、清空目錄。
#encoding=utf-8#適用於python3.5+import os, sys, time, shutil#清空目錄def ClearDir(dir): print('ClearDir ' + dir + '...') for entry in os.scandir(dir): if entry.name.startswith('.'): continue if entry.is_file(): os.remove(entry.path) #刪除檔案 else: shutil.rmtree(entry.path) #刪除目錄
13、切換目錄。
os.chdir(newpath)
14、open常用模式。
'r': 唯讀(預設。如果檔案不存在,則拋出錯誤。)
'w': 唯寫(如果檔案不存在,則自動建立檔案。)
'a': 追加
'r+': 讀寫
15、由全路徑名的到路徑和檔案名稱。
>>> pathfile = r'D:\abc\def\ghi.txt'>>> os.path.dirname(pathfile)'D:\\abc\\def'>>> os.path.basename(pathfile)'ghi.txt'
16、擷取檔案大小。
os.path.getsize(pathfile)#單位為位元組(Byte)
17、擷取當前檔案目錄絕對路徑。
import os, sysif __name__ == "__main__": os.chdir('E:\\') print(sys.path[0]) print(os.path.abspath('.')) print(os.path.dirname(os.path.abspath(__file__)))