# 文件及目錄操作 ###### tags: `人生苦短,我學Python` ## 建立和打開文件 * 建立文件可以使用 ```python= file = open(filename[,mode[,buffering]]) # 默認打開mode => "r" ``` * 打開一個不存在的文件時,應該先建立文件 ```python= print("開始建立新文件") file = open("newfile.txt", "w") ``` * 結果 ![](https://i.imgur.com/5dJACdk.png) * 以二進制的方式打開文件 ```python= file = open("test.jpg", "rb") print(file) ``` * 打開文件的一般形式 ```python= file = open("test.txt", "rw", encoding = "utf-8") ``` ## 關閉文件 * 使用close() ```python= file.close() # file => 文件名 ``` ## 打開文件時,使用with語句 * 使用with就可以處理忘記關閉文件的問題 ```python= with expression as target: with-body ``` * 範例 ```python= with open("1.txt", "r", encoding = "utf-8") as file: pass ``` ## 寫入文件 * 使用write()方法 ```python= file.write("write SomeThing") ``` * 使用剛才的範例並追加 ```python= file = open("1.txt", "w+", encoding="utf-8") file.write("我想寫入一些東西進去檔案裡") file.close() ``` :::success :warning: 寫入文件後,一定要關閉文件,否則寫入的內容不會保存到文件中。 ::: ## 讀取文件 * 讀取指定字符 ```python= # file.read([size]) file.read() # 全部印出 ``` * 使用seek()語法 ```python= file.seek(offset,[,whence]) whence => 0表示從頭,1表示從當前位置開始計算,2表示從尾巴開始,默認為0 ``` * 範例 ```python= with open("1.txt", "r") as file: file.seek(5) string = file.read(5) print(string) # offset => 漢字2字符,英文與其他1字符 ``` * 讀取一行的情況 ```python= file.readline() ``` * 讀取全部 ```python= file.readlines() ``` ## 目錄操作 :::success 又稱文件夾。用於分層保護文件。 ::: * 先導入os模組 ```python= import os ``` * 相對路徑 ```python= print(os.getcwd()) # 輸出當前目錄C:\Users\a9132\Desktop\python ``` :::success 在指令路徑時可以在路徑前加上r(R),這樣所有字符都會按原樣輸出。 ::: * 絕對路徑 ```python= # os.path.abspath(path) print(os.path.abspath(r"1.txt")) # C:\Users\a9132\Desktop\python\1.txt ``` * 拼接路徑 ```python= # os.path.join(path1[,path2...]) print(os.path.join(r"C:\Users\a9132\Desktop", "python\1.txt")) # C:\Users\a9132\Desktop\python.txt ``` ## 判斷目錄是否存在 * 使用exists()函數 ```python= # os.path.exists(path) print(os.path.exists(r"C:\Users\a9132\Desktop")) # True ``` ## 建立目錄 * 建立資料夾 ```python= # os.mkdir(path, mode=0o777) # 建立資料夾 os.mkdir(r"C:\Users\a9132\Desktop\python\test") ``` * 建立成功 ![](https://i.imgur.com/Pjr3ghG.png) * 如果存在... ```python= if not os.path.exists(path): os.mkdir(path) else: print("該資料夾已存在") ``` * 可以使用makedirs建立資料夾的次級資料夾 ```python= os.makedirs(name, mode) ``` ## 刪除目錄 * 使用rmdir()函數 ```python= os.rmdir(path) ``` :::success 該函數只能刪除空目錄,如果想刪除非空目錄,就需要使用...... ```python= import shutil shutil.rmtree(path) ``` ::: ## 遍歷目錄 * 使用walk()函數 ```python= # os.walk(top[,topdown][,onerror][,followlinks]) # 返回(dirpath, dirnames, filenames) # 只在UNIX、windows系統有效 import os tup = os.walk(path) for tup1 in tup: print(tup1, "\n") ``` * 結果 ![](https://i.imgur.com/fnJ5ziK.png) ## 刪除文件 * 使用remove()函數 ```python= # os.remove(path) os.remove(1.txt) ``` ## 文件重新命名 * 使用os.rename()函式 ```python= # os.rename("src", "dst") os.rename("1.txt", "new.txt") ``` * 結果 ![](https://i.imgur.com/TetQPDi.png) ## 獲取文件基本資訊 * 使用os.stat()函數 ```python= import os fileinfo = os.stat("new.txt") print("最後一次修改時間: ", fileinfo.st_mtime) # 最後一次修改時間: 1628472453.0625432 ``` * 同款資訊 ```python= st_mode: inode 保護模式 st_ino:inode節點號。 st_dev: inode 駐留的設備。 st_nlink: inode 的鏈接數。 st_uid: 所有者的用戶ID。 st_gid: 所有者的組ID。 st_size: 普通文件以字節為單位的大小;包含特定特定文件的數據。 st_atime: 上次訪問的時間。 st_mtime: 最後一次修改的時間。 st_ctime:由操作系統報告的“ctime”。在部分系統上(如Unix)是最新的元數據更改時間,在其他系統上(如Windows)是創建時間(詳細信息參見平台的文檔)。 # 取自菜鳥教程 ``` {%hackmd S1DMFioCO %}