python之檔案系統操作(os模組)

來源:互聯網
上載者:User

標籤:rem   順序   txt   int   pre   logs   pdo   指定   遍曆   

檔案系統操作(os模組)

 1 import os 2  3 file_name = "D:\\test_data\\1.txt" 4 file_name_2 = "D:\\test_data\\3.txt" 5 # 刪除檔案 6 # os.remove(file_name) 7  8 # 檔案重新命名 9 # os.rename(file_name, file_name_2)10 11 # 刪除空目錄12 dir_name = ‘D:\\test_data\\1‘13 # os.removedirs(dir_name)14 15 dir = ‘D:\\test_data\\1‘16 # 擷取指定目錄下的檔案清單17 file_lists = os.listdir(dir)18 print("擷取指定目錄下的檔案清單:", file_lists)19 # 擷取檔案建立時間20 file_time = os.path.getmtime(dir + "\\" + file_lists[-1])21 print("檔案建立時間:", file_time)22 # 判斷檔案是否是目錄23 file_is_dir = os.path.isdir(dir + "\\" + file_lists[-1])24 print("檔案是否是目錄:", file_is_dir)25 # 組裝檔案完整路徑26 file_path = os.path.join(dir, file_lists[-1])27 print("檔案的完整路徑:", file_path)28 # 擷取檔案大小29 file_size = os.path.getsize(file_path)30 print("檔案大小:", file_size)

運行結果:

1 擷取指定目錄下的檔案清單: [‘2-1‘, ‘2-1.txt‘, ‘2-2‘, ‘2-2.txt‘]2 檔案建立時間: 1500290284.20891983 檔案是否是目錄: False4 檔案的完整路徑: D:\test_data\1\2-2.txt5 檔案大小: 3

 

檔案遍曆:

  • 遍曆目錄下所有檔案包括子目錄
  • os.walk功能:遞迴遍曆目錄下的檔案和子目錄,參數(需要遍曆的目錄,排序=ture為順序)
  • 返回三個值:目前的目錄、目前的目錄下的目錄列表和目前的目錄下的檔案清單
1 for file_path, dirs, file_names in os.walk(dir_name, topdown=True):2     print("----------------------------------")3     print("原名:", file_path, dirs, file_names)4     for file_name in file_names:  # 遍曆檔案名稱列表5         print("-" * 20)6         print("目錄下檔案路徑:", os.path.join(file_path, file_name))7         file_name_temp = os.path.join(file_path, file_name)  # 組裝完整檔案名稱,含路徑8         list = file_path.split("\\")  # 切分檔案名稱,方便擷取父目錄名稱9         print("檔案父目錄名:", list[-1])

運行結果:

 1 ---------------------------------- 2 原名: D:\1 [‘2-1‘, ‘2-2‘] [‘2-1.txt‘, ‘2-2.txt‘] 3 ---- 4 目錄下檔案路徑: D:\1\2-1.txt 5 檔案父目錄名: 1 6 ---- 7 目錄下檔案路徑: D:\1\2-2.txt 8 檔案父目錄名: 1 9 ----------------------------------10 原名: D:\1\2-1 [‘3-1‘, ‘3-2‘] [‘3-1.txt‘]11 ----12 目錄下檔案路徑: D:\1\2-1\3-1.txt13 檔案父目錄名: 2-114 ----------------------------------15 原名: D:\1\2-1\3-1 [] [‘4-1.txt‘]16 ----17 目錄下檔案路徑: D:\1\2-1\3-1\4-1.txt18 檔案父目錄名: 3-119 ----------------------------------20 原名: D:\1\2-1\3-2 [] []21 ----------------------------------22 原名: D:\1\2-2 [] []

 

python之檔案系統操作(os模組)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.