【问题标题】:How to create a new text file using Python如何使用 Python 创建一个新的文本文件
【发布时间】:2018-08-04 04:10:08
【问题描述】:

我正在练习用 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')

【问题讨论】:

  • 如果您不向我们展示您的代码,我们无法告诉您您的代码有什么错误。
  • @JohnAnderson 完成。
  • @JustHalf 当我在 PyCharm 中运行此代码时,它不会引发错误?
  • 该代码不会打开文件,它只是创建一个路径对象。
  • 您使用的 IDE 在这里无关紧要。它不会影响您从中运行的 Python 代码的行为。

标签: python python-2.7


【解决方案1】:
# 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

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

【讨论】:

  • 需要说明的是,使用with open(...)时不需要调用f.close()
【解决方案2】:

看来你在调用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

查看Python2.7Python3.6 的文档

-- 编辑--

正如 chepner 在下面的评论中所说,最好使用withstatement 来执行此操作(它保证文件将被关闭)

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

【讨论】:

    猜你喜欢
    • 2014-01-04
    • 1970-01-01
    • 1970-01-01
    • 2019-06-30
    • 2021-02-23
    • 2018-01-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多