如何使用 Python 创建一个新的文本文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/48959098/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to create a new text file using Python
提问by Just Half
I'm practicing the management of .txt files in python. I've been reading about it and found that if I try to open a file that doesn't exists yet it will create it on the same directory from where the program is being executed. The problem comes that when I try to open it, I get this error:
我正在练习python中.txt文件的管理。我一直在阅读它,发现如果我尝试打开一个尚不存在的文件,它将在执行程序的同一目录中创建它。问题来了,当我尝试打开它时,出现此错误:
IOError: [Errno 2] No such file or directory: 'C:\Users\myusername\PycharmProjects\Tests\copy.txt'.
IOError: [Errno 2] 没有这样的文件或目录:'C:\Users\myusername\PycharmProjects\Tests\copy.txt'。
I even tried specifying a path as you can see in the error.
我什至尝试指定一个路径,如您在错误中看到的那样。
import os
THIS_FOLDER = os.path.dirname(os.path.abspath(__file__))
my_file = os.path.join(THIS_FOLDER, 'copy.txt')
回答by Bentaye
Looks like you forgot the mode parameter when calling open
, try w
:
看起来您在调用时忘记了 mode 参数open
,请尝试w
:
file = open("copy.txt", "w")
file.write("Your text goes here")
file.close()
The default value is r
and will fail if the file does not exist
默认值是r
并且如果文件不存在将失败
'r' open for reading (default)
'w' open for writing, truncating the file first
Other interesting options are
其他有趣的选择是
'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
See Doc for Python2.7or Python3.6
-- EDIT --
- 编辑 -
As stated by chepnerin the comment below, it is better practice to do it with a with
statement (it guarantees that the file will be closed)
正如chepner在下面的评论中所说,最好用with
语句来做(它保证文件将被关闭)
with open("copy.txt", "w") as file:
file.write("Your text goes here")
回答by r3t40
# 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
There are many more methods but these two are most common. Hope this helped!
还有更多的方法,但这两种是最常见的。希望这有帮助!
回答by Pravin Ganeshanraj
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 2shush
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
回答by Dhiman Dutta
file = open("path/of/file/(optional)/filename.txt", "w") #a=append,w=write,r=read
any_string = "Hello\nWorld"
file.write(any_string)
file.close()