OSError: [Errno 22] Invalid argument錯誤解決方案
阿新 • • 發佈:2022-05-19
在做檔案讀取寫入操作的時候遇見OSError: [Errno 22] Invalid argument: 'F:\\pythonProject\\Api\\common\\2022-03-11_15:37:23test.txt'的報錯,單獨的打印出檔案路徑明明是正確,但使用python open()函式讀寫檔案時就會報該錯誤
錯誤程式碼:
import os import time now = time.strftime("%Y-%m-%d_%H:%M:%S", time.localtime()) file_path = os.path.realpath(__file__) file_name = os.path.join(os.path.split(file_path)[0], now+'test.txt') with open(file_name, 'w+') as file: print(file)
報錯內容如下:
要特別注意,以當前時間命名檔案時,時間格式化:"%Y-%m-%d_%H:%M:%S" 修改為"%Y-%m-%d_%H_%M_%S" 就能避免這種錯誤,注意一定格式化一定不要用冒號:
修改後的程式碼:
import os import time now = time.strftime("%Y-%m-%d_%H_%M_%S", time.localtime()) #一定要注意這裡的時間格式,不要用冒號 file_path = os.path.realpath(__file__) file_name = os.path.join(os.path.split(file_path)[0], now+'test.txt') with open(file_name, 'w+') as file: print(file)
執行結果如下: