【问题标题】:Can't write to a .txt file in Python无法在 Python 中写入 .txt 文件
【发布时间】:2017-06-16 07:05:41
【问题描述】:

这是我的代码:

import os
os.chdir("C:\\Users\\satvi_000\\Downloads")

if os.path.exists('new_file.txt')==False:  
    create_file= open("new_file.txt",'w')  #This is just to  create the file 
                                                  #in case it doesn't exist
    create_file.close()
file= open('new_file.txt','r+')

data= file.read()

file.write("blah blah blah ")

我想创建一个文件(如果它不存在)并向其中写入一些数据。我正在将其作为更大程序的一部分进行,并单独对其进行测试以查看问题所在,但我还不能完全弄清楚。 我将在更大的程序中一次又一次地写入该文件,并且每次运行程序时也会修改该文件。 这里出了什么问题?

【问题讨论】:

  • 您无需将os.path.exists 与布尔值进行比较。它已经返回一个布尔值。你可以if not os.path.exists(...) 代替。
  • 你有什么问题?
  • 为我工作(如果我更改 chdir 名称)
  • “这里出了什么问题?”这就是我们想知道的。这段代码有什么问题?它会抛出错误吗?它会更新错误的文件吗?它是否将错误的数据写入文件?
  • 最好不要使用os.chdir,而是将路径添加到您的open调用:filename = r'C:\Users\satvi_000\Downloads\new_file.txt'; create_file = open(filename, 'w')

标签: python file file-writing


【解决方案1】:

也许这对你有帮助

Python Print String To Text File

尝试使用with open("new_file.txt", "w") as text_file:

【讨论】:

    【解决方案2】:

    尝试最后关闭文件。 file.close()

    【讨论】:

      【解决方案3】:
      import os
      os.chdir("C:\\Users\\satvi_000\\Downloads")
      
      if os.path.exists('new_file.txt')==False:  
          create_file= open("new_file.txt",'w')  #This is just to  create the file 
                                                        #in case it doesn't exist
          create_file.close()
      file= open('new_file.txt','r+')
      
      data= file.read()
      
      file.write("blah blah blah ")
      file.close()
      

      【讨论】:

        【解决方案4】:

        当您一次又一次地写入文件时,它会不断修改文件,删除同一文件中的早期数据。 如果要更新文件,请使用附加 (a) 权限打开文件,而不是使用写入操作。

        并且在您的代码中,当您打开具有“w”权限的文件时,如果该文件不存在,它将默认创建该文件。并且可以直接写入文件。 你不需要重新打开它,它已经打开了。

        谢谢。

        【讨论】:

        • 欢迎来到 Stack Overflow。谢谢您的回答。有两件事要考虑作为改进。 1)除了描述代码的变化;拥有一个基于 OP 示例的完整(固定)代码示例也很有用。 2) 无需在您的回答中添加 Thanks.。对于这里的大多数用户来说,这是一种不必要的干扰;让你的答案尽可能简洁。更多提示请参考How do I write a good answer?;并通过tour 了解 Stack Overflow 的工作原理。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-07-15
        • 1970-01-01
        • 1970-01-01
        • 2014-01-23
        相关资源
        最近更新 更多