Python檔案與檔案夾常見基本操作總結,

來源:互聯網
上載者:User

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__)))

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.