Python文件與文件夾常見基本操作總結(jié)
本文實例講述了Python文件與文件夾常見基本操作。分享給大家供大家參考,具體如下:
1、判斷文件(夾)是否存在。
os.path.exists(pathname)
2、判斷路徑名是否為文件。
os.path.isfile(pathname)
3、判斷路徑名是否為目錄。
os.path.isdir(pathname)
4、創(chuàng)建文件。
os.mknod(filename) #windows下不可用 open(filename, "w") #記得要關(guān)閉
5、復(fù)制文件。
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、創(chuàng)建目錄。
os.mkdir(pathname) #創(chuàng)建單級目錄 os.makedirs(pathname) #遞歸創(chuàng)建多級目錄
9、復(fù)制目錄。
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': 只寫(如果文件不存在,則自動創(chuàng)建文件。)
'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) #單位為字節(jié)(Byte)
17、獲取當前文件目錄絕對路徑。
import os, sys if __name__ == "__main__": os.chdir('E:\\') print(sys.path[0]) print(os.path.abspath('.')) print(os.path.dirname(os.path.abspath(__file__)))
更多關(guān)于Python相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Python文件與目錄操作技巧匯總》、《Python文本文件操作技巧匯總》、《Python URL操作技巧總結(jié)》、《Python圖片操作技巧總結(jié)》、《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python Socket編程技巧總結(jié)》、《Python函數(shù)使用技巧總結(jié)》、《Python字符串操作技巧匯總》及《Python入門與進階經(jīng)典教程》
希望本文所述對大家Python程序設(shè)計有所幫助。
相關(guān)文章
Python中執(zhí)行存儲過程及獲取存儲過程返回值的方法
這篇文章主要介紹了Python中執(zhí)行存儲過程及獲取存儲過程返回值的方法,結(jié)合實例形式總結(jié)分析了Python調(diào)用存儲過程的常用方法與相關(guān)操作注意事項,需要的朋友可以參考下2017-10-10Django+Bootstrap實現(xiàn)計算器的示例代碼
本文主要介紹了Django+Bootstrap實現(xiàn)計算器的示例代碼,文中通過示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-11-11Python??reduce()函數(shù)的用法示例代碼
reduce函數(shù)原本在python2中也是個內(nèi)置函數(shù),不過在python3中被移到functools模塊中,這篇文章主要介紹了Python reduce()函數(shù)的用法,需要的朋友可以參考下2023-05-05