1. 程式人生 > >Python檔案及資料夾操作

Python檔案及資料夾操作

轉載自:http://www.cnblogs.com/feeland/    

    我們經常會與檔案和目錄打交道,對於這些操作,python可以使用 os 及 shutill 模組,其中包含了很多操作檔案和目錄的函式。

    os 可以執行簡單的資料夾及檔案操作,引入用  import os,可用  help(os)  或是  dir(os)  檢視其用法。注意有些函式在os模組中,有的是在os.path模組中。

    shutil 模組提供了大量的檔案的高階操作,特別針對檔案拷貝和刪除。主要功能為目錄和檔案操作以及壓縮操作。須引入 import shutil  ,具體 help。本文僅介紹移動、複製及刪除。

 

    可先在 D:\ 下建立資料夾 Python_os , 再在其下建立資料夾 os, 再在其下建立 test.txt;之後的示例會在該資料夾下操作

      

  判斷路徑或檔案

    os.path.isabs(...)      # 判斷是否絕對路徑

    os.path.exists(...)     # 判斷是否真實存在

    os.path.isdir(...)       # 判斷是否是個目錄

    os.path.isfile(...)       # 判斷是否是個檔案

  注意:   把兩個路徑合成一個時,不要直接拼字串,而要通過 os.path.join(part1,part2) 函式,這樣可以正確處理不同作業系統的路徑分隔符。在Linux/Unix/Mac下,os.path.join()返回這樣的字串:    part1/part2

Try

      而Windows下會返回這樣的字串:  part1\part2

複製程式碼

 1 import os
 2 import shutil
 3 
 4 file_dir = "D:\\Python_os\\os"                          # 注意 \\ ;windows 下是這麼表示的;Linux 和 Mac 是 /
 5 file_name = "test.txt"
 6 file_abs = os.path.join(file_dir, file_name)            # os.path.join(...) 表示路徑連結
 7 
 8 
 9 '''判斷路徑或檔案'''
10 print (1,os.path.isabs(file_dir))                       # 判斷是否絕對路徑
11 print (2,os.path.isabs(file_name))                        
12 print (3,os.path.isabs(file_abs))                        
13 print (4,os.path.exists(file_abs))                      # 判斷是否真實存在
14 print (5,os.path.exists(os.path.join(file_dir,"xxx")))                
15 print (6,os.path.isdir(file_dir))                       # 判斷是否是個目錄
16 print (7,os.path.isdir(file_abs))        
17 print (8,os.path.isfile(file_dir))                      # 判斷是否是個檔案
18 print (9,os.path.isfile(file_abs))        

複製程式碼

     執行結果:  

 

  路徑名、檔名分隔

    os.path.split(...)            # 分隔目錄和檔名/資料夾名         

    os.path.splitdrive(...)        # 分隔碟符(windows系統)     

    os.path.splitext(...)           # 分隔檔案和副檔名

      執行結果:  

      這些合併、拆分路徑的函式並不要求目錄和檔案要真實存在,它們只對字串進行操作。

 

  工作目錄及建立資料夾操作

    os.getcwd()       # 獲取當前工作目錄

    os.chdir(...)       # 改變工作目錄

    os.listdir(...)      # 列出目錄下的檔案

    os.mkdir(...)      # 建立單個目錄        注意:建立多級用 os.makedirs()

    os.makedirs(...)    # 建立多級目錄

複製程式碼

 1 import os
 2 
 3 file_dir = "D:\\Python_os\\os"    
 4 
 5 print (os.getcwd())                                # 獲取當前工作目錄
 6 os.chdir(file_dir)                                 # 改變工作目錄
 7 print (os.getcwd())    
 8 print (os.listdir(file_dir))                       # 列出當前工作目錄的所有檔案 Python2 不支援 os.listdir()    Python3 會列出當前工作目錄下的所有檔案      
 9 os.mkdir("test_mkdir")                             # 在當前工作目錄下建立資料夾 test_mkdir;注意不可存在相同資料夾,不然會報錯
10 os.makedirs("test_mkdir\\test1")
11 os.chdir(".\\test_mkdir")                          # . 表示本級目錄; .. 表示上級目錄
12 print (os.getcwd())    
13 for i in range(2,6):                               # 使用for迴圈等,可方便的建立多個資料夾
14     dir_name = "test" + str(i)
15     os.mkdir(dir_name)    

複製程式碼

     在執行了上述例項程式碼後,os 資料夾中新建了空的 test_mkdir 資料夾,而 test_dir 資料夾下也新建出了 test1 至 test5 的空資料夾

       

 

    建立資料夾可能會出錯,原因具體有:(1) path 已存在時(不管是檔案還是資料夾)  (2) 驅動器不存在  (3) 磁碟已滿  (4) 磁碟是隻讀的或沒有寫許可權

    檔案的建立及操作參見下一章節

 

  刪除資料夾/檔案

    os.rmdir(...)            # 刪除空資料夾                     注意:必須為空資料夾  如需刪除資料夾及其下所有檔案,需用 shutil

    os.remove(...)                   # 刪除單一檔案

    shutil.rmtree(...)               # 刪除資料夾及其下所有檔案

    在上方示例的資料夾基礎上,操作刪除 test1 資料夾 (空資料夾可用 os.rmdir() ),刪除 test_mkdir 及其下所有檔案();示例程式碼如下

複製程式碼

 1 import os
 2 import shutil
 3 
 4 file_dir = "D:\\Python_os\\os"                    
 5 
 6 ''' 刪除檔案/資料夾 '''
 7 os.chdir(file_dir+"\\test_mkdir")                    
 8 print(os.getcwd())                                    # 確保當前工作目錄
 9 print(os.listdir(os.getcwd()))                        # 檢視當前資料夾下所有檔案    
10 os.rmdir("test1")                                     # 刪除 test1 資料夾(空資料夾)
11 print(os.listdir(os.getcwd()))    
12 os.chdir("..\\")
13 print(os.getcwd())                                    # 切換到上級目錄
14 print(os.listdir(os.getcwd()))
15 shutil.rmtree("test_mkdir")                           # 刪除 test_mkdir 及其下所有檔案

複製程式碼

     可見執行結果如下;產生異常的可能原因:  (1) 路徑不存在 (2) 路徑子目錄中有檔案或下級子目錄(os.rmdir) (3) 沒有操作許可權或只讀

        

     只是刪除單一檔案,則用   os.remove("test.txt")   即可;產生異常的可能原因:  (1) 檔案不存在   (2) 對該檔案沒有操作許可權或只讀。

     

 

  重新命名資料夾/檔案

    可對某一檔案或資料夾重新命名   os.rename(oldfileName, newFilename)  

    在os資料夾中新建資料夾 test,檔案 test.txt    

複製程式碼

1 ''' 重新命名資料夾/檔案 '''
2 os.chdir(file_dir)
3 print(os.listdir(os.getcwd()))
4 os.rename("test","test1")    
5 os.rename("test.txt","test1.txt")                # 重新命名,注意需要帶副檔名
6 print(os.listdir(os.getcwd()))

複製程式碼

    可見執行結果如下;產生異常的可能原因:  (1) oldfilename 舊檔名不存在(檔案須帶副檔名)   (2)newFilename 新檔案已經存在

    

    注意:新檔案的副檔名不能遺漏,理論上需要保持型別一致;但這也不失為改檔案型別的一種方式(相當於直接改檔案的副檔名)

    

  

    複製、移動資料夾/檔案

    須使用 shutil 模組,引入 import shutil 

    shutil.copyfile("old","new")       # 複製檔案,都只能是檔案

    shutil.copytree("old","new")     # 複製資料夾,都只能是目錄,且new必須不存在

    shutil.copy("old","new")           # 複製檔案/資料夾,複製 old 為 new(new是檔案,若不存在,即新建),複製 old 為至 new 資料夾(資料夾已存在)

    shutil.move("old","new")          # 移動檔案/資料夾至 new 資料夾中

    我們現在 D:\ 下建立新資料夾 Python_shutil ,然後工作目錄切到該目錄,直接使用 Python 來操作吧,參考程式碼如下:

複製程式碼

1 import os
2 import shutil
3 
4 os.chdir("D:\\")
5 os.mkdir("Python_shutil")
6 file_dir = "D:\\Python_shutil"
7 os.chdir(file_dir)

 

 

    為演示覆制、移動操作,我們在該資料夾下手動操作 新建資料夾 test_org、 test_copy 及 test_move; 新建檔案 test.txt  test1.txt , 兩者內容不同

         

    Python 複製、移動的操作示例程式碼如下:

複製程式碼

 1 import os
 2 import shutil
 3 
 4 file_dir = "D:\\Python_shutil"
 5 os.chdir(file_dir)
 6 shutil.copyfile("test_org.txt","test_copy.txt")        # copy test_org.txt 為 test_copy.txt 若存在,則覆蓋
 7 shutil.copyfile("test_org.txt","test1.txt")            # 存在,覆蓋
 8 shutil.copytree("test_org","test_copytree")            # copy test_org 為 test_copytree(不存在的新目錄)
 9 shutil.copy("test_org.txt","test_copy1.txt")           # 同 copyfile
10 shutil.copy("test_org.txt","test_copy")                # 將檔案 copy 至 目標資料夾中(須存在)
11 shutil.copy("test_org.txt","test_xxx")                 # 將檔案 copy 至 目標檔案(該檔案可不存在,注意型別!)
12 print os.listdir(os.getcwd())
13 shutil.move("test_org.txt","test_move")                # 將檔案 move 至 目標資料夾中
14 shutil.move("test_org","test_move")                    # 將資料夾 move 至 目標資料夾中
15 print os.listdir(os.getcwd())