本文實例講述了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__)))更多關于Python相關內容感興趣的讀者可查看本站專題:《Python文件與目錄操作技巧匯總》、《Python文本文件操作技巧匯總》、《Python URL操作技巧總結》、《Python圖片操作技巧總結》、《Python數據結構與算法教程》、《Python Socket編程技巧總結》、《Python函數使用技巧總結》、《Python字符串操作技巧匯總》及《Python入門與進階經典教程》
希望本文所述對大家Python程序設計有所幫助。
新聞熱點
疑難解答
圖片精選