简体   繁体   English

无法在 Python 中写入 .txt 文件

[英]Can't write to a .txt file in Python

This is my code:这是我的代码:

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

I want to create a file( if it doesn't already exist) and write some data to it.我想创建一个文件(如果它不存在)并向其中写入一些数据。 I'm doing this as a part of a larger program and tested it separately to see what the problem was and I can't quite figure it out yet.我正在做这个作为一个更大的程序的一部分并单独测试它以查看问题是什么,我还不能完全弄清楚。 I will be writing to this file again and again in the larger program, and the file will also be modified everytime the program is run.我会在更大的程序中一次又一次地写入这个文件,并且每次程序运行时都会修改该文件。 What's going wrong here?这里出了什么问题?

May be this can help you也许这可以帮助你

Python Print String To Text File Python 打印字符串到文本文件

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

Try closing the file in the end.最后尝试关闭文件。 file.close()

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

As you are writing the file again and again, so it will keep modifying the file, erasing earlier data present in the same file.当您一次又一次地写入文件时,它会不断修改文件,擦除同一文件中存在的较早数据。 If you want to update the file, open the file with append (a) permission and not with write operation.如果要更新文件,请使用 append (a) 权限而不是写操作打开文件。

And in your code, the moment you open a file with 'w' permission, it will create the file by default if the file does not exist.在您的代码中,当您使用 'w' 权限打开文件时,如果该文件不存在,它将默认创建该文件。 And you can directly write into the file.并且可以直接写入文件。 You dont need to reopen it, it is already open.你不需要重新打开它,它已经打开了。

Thanks.谢谢。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM