如何使用Python创建新的文本文件

时间:2018-02-24 03:33:53

标签: python python-2.7

我在python中练习.txt文件的管理。我一直在阅读它,发现如果我尝试打开一个不存在的文件,它会在程序执行的同一目录上创建它。问题是,当我尝试打开它时,我收到此错误:

  

IOError:[Errno 2]没有这样的文件或目录:   ' C:\ Users \用户名为myUsername \ PycharmProjects \测试\ copy.txt&#39 ;.

我甚至尝试在错误中看到指定路径。

ProgressDialog

4 个答案:

答案 0 :(得分:32)

在调用open时,您似乎忘记了模式参数,请尝试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

查看Python2.7Python3.6

的文档

- 编辑 -

如下面评论中的 chepner 所述,最好使用with语句(它保证文件将被关闭)

with open("copy.txt", "w") as file:
    file.write("Your text goes here")

答案 1 :(得分:0)

# 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
    f.close()                                   # Close file

还有更多的方法,但这两种是最常见的。希望这会有所帮助!

答案 2 :(得分:0)

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

答案 3 :(得分:0)

    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()