我正在python中练习.txt文件的管理.我一直在阅读它,发现如果我尝试打开一个不存在的文件,它将在程序执行的同一目录上创建它.问题是,当我尝试打开它时,我收到此错误:
IOError: [Errno 2] No such file or directory:
‘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时忘记了mode参数,试试w:
file = open("copy.txt", "w")
file.write("Your text goes here")
file.close()
默认值为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
– 编辑 –
正如chepner在下面的评论中所述,更好的做法是使用withstatement(它保证文件将被关闭)
with open("copy.txt", "w") as file:
file.write("Your text goes here")
标签:python,python-2-7
来源: https://codeday.me/bug/20191007/1868977.html