Can';t在Python中写入.txt文件

Can';t在Python中写入.txt文件,python,file,file-writing,Python,File,File Writing,这是我的代码: 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 doe

这是我的代码:

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 ")
我想创建一个文件(如果它还不存在)并向其中写入一些数据。我把它作为一个更大的程序的一部分来做,并对它进行了单独的测试,看看问题出在哪里,但我还不能完全弄清楚。 我将在更大的程序中一次又一次地写入此文件,并且每次程序运行时都会修改此文件。
这里出了什么问题?

这可能对你有帮助


尝试使用打开的
(“new_file.txt”,“w”)作为文本文件:

最后尝试关闭文件。
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()

file.close()

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

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


谢谢。

您不需要将
os.path.exists
与布尔值进行比较。它已经返回一个布尔值。如果不是os.path.exists(…),您可以
。您的问题是什么?对我有效(如果我更改chdir名称)“这里出了什么问题?”这就是我们想知道的。这个代码有什么问题?它会抛出错误吗?它是否更新了错误的文件?它是否将错误的数据写入文件?最好不要使用
os.chdir
,而是将路径添加到
open
调用:
filename=r'C:\Users\satvi_000\Downloads\new_file.txt';create_file=open(文件名为'w')
。欢迎使用堆栈溢出。谢谢你的回答。作为改进的两件事。1) 除了描述代码更改外;基于OP的示例,有一个完整的(固定的)代码示例也很有用。2) 不用再加了,谢谢。在你的回答中。对于这里的大多数用户来说,这是一种不必要的干扰;你的回答要尽可能简洁。有关更多提示,请参阅;并学习如何使用堆栈溢出。