我很難相信 python 在 2020 年仍然存在創(chuàng)建文件的問題......所以,我假設(shè)它是 windows 或我......這是帶有輸出的代碼。我嘗試了 w、w+、wt 模式,錯誤消息如下。使用 w, w+, wt 的全部意義在于如果文件不存在則創(chuàng)建該文件我已更改為使用 Path.touch,然后使用僅給出和錯誤輸入的 a、a+ 模式import sysprint("Python version:")print (sys.version)import platformprint("Platform: {} - {} - {}".format(platform.system(), platform.release(), platform.version()))from pathlib import Pathoutput = 'hello world!'save_dir = Path.cwd().joinpath("./sw_out")if(save_dir.exists() == False): save_dir.mkdir() print("dir exists now: {}".format(save_dir.exists()))debug_file = save_dir.joinpath("my_debug.txt")#debug_file.touch(exist_ok=True)print(str(debug_file))with(open(debug_file), 'w+') as f: f.write(output)f.close()Python version:3.7.6 | packaged by conda-forge | (default, Dec 26 2019, 23:30:11) [MSC v.1916 64 bit (AMD64)]Platform: Windows - 10 - 10.0.17763dir exists now: TrueC:\users\me\project\sw_out\my_debug.txt---------------------------------------------------------------------------FileNotFoundError Traceback (most recent call last)<ipython-input-19-447d2a994262> in <module> 16 #debug_file.touch(exist_ok=True) 17 print(str(debug_file))---> 18 with(open(str(debug_file)), 'w+') as f: 19 f.write(output) 20 f.close()FileNotFoundError: [Errno 2] No such file or directory: 'C:\\users\\me\\project\\sw_out\\my_debug.txt'
Python open 不會根據(jù)文檔創(chuàng)建文件
拉風(fēng)的咖菲貓
2022-10-05 16:58:50