Jus*_*alf 17 python python-2.7
我正在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')
Run Code Online (Sandbox Code Playgroud)
Ben*_*aye 48
看起来你在调用时忘记了mode参数open,试试w:
file = open("copy.txt", "w")
file.write("Your text goes here")
file.close()
Run Code Online (Sandbox Code Playgroud)
r如果文件不存在,则默认值为和将失败
'r' open for reading (default)
'w' open for writing, truncating the file first
Run Code Online (Sandbox Code Playgroud)
其他有趣的选择是
'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
Run Code Online (Sandbox Code Playgroud)
请参阅Doc for Python2.7或Python3.6
- 编辑 -
正如chepner在下面的评论中所说,最好用with语句来做(它保证文件将被关闭)
with open("copy.txt", "w") as file:
file.write("Your text goes here")
Run Code Online (Sandbox Code Playgroud)
r3t*_*t40 10
# Method 1
f = open("Path/To/Your/File.txt", "w") # 'r' for reading and 'w' for writing
f.write("Hello World from " + f.name) # Write inside file
f.close() # Close file
# Method 2
with open("Path/To/Your/File.txt", "w") as f: # Opens file and casts as f
f.write("Hello World form " + f.name) # Writing
# File closed automatically
Run Code Online (Sandbox Code Playgroud)
还有更多的方法,但这两种是最常见的。希望这有帮助!