我正在练习用 python 管理 .txt 文件。我一直在阅读有关它的内容,发现如果我尝试打开一个尚不存在的文件,它将在执行程序的同一目录中创建该文件。问题来了,当我尝试打开它时,出现以下错误:
IOError: [Errno 2] 没有这样的文件或目录:
'C:\Users\myusername\PycharmProjects\Tests\copy.txt'。
我什至尝试指定一个路径,如您在错误中看到的那样。
import os
THIS_FOLDER = os.path.dirname(os.path.abspath(__file__))
my_file = os.path.join(THIS_FOLDER, 'copy.txt')
看来您在调用时忘记了模式参数open
, try w
:
with open("copy.txt", "w") as file:
file.write("Your text goes here")
默认值为r
如果文件不存在将会失败
'r' open for reading (default)
'w' open for writing, truncating the file first
其他有趣的选择是
'x' open for exclusive creation, failing if the file already exists
'a' open for writing, appending to the end of the file if it exists
请参阅文档Python2.7 https://docs.python.org/2.7/library/functions.html#open or Python3.6 https://docs.python.org/3.6/library/functions.html#open
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)