Python中的stdout打印但无法写入文件

2024-10-01 15:35:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我突然对Python的这种奇怪行为感到非常沮丧。我一直在写各种各样的数据,但从今天早上开始,似乎就不起作用了。我在发帖前已经提到了这些:

已经尝试了以下所有命令,但它不向删除.txt文件。怎么回事?在

fl=open('delete.txt','w')
fl.write(msg) <--Doesnt work,tried this also
fl.write('%s' %msg) <--Doesnt work,tried this also
fl.write("at least write this") <-- Doesnt work,tried this also
print (msg) <- WORKS

代码:

^{2}$

更多代码:

type(mes) = str
mes="omg would love front yard"

Tags: to代码txtmsgthisfilewritework
2条回答

当写入这样的文件句柄时,需要显式刷新输出流。在

f = open("test.txt", "w")
f.write("this is a test\n")
# no text in the output file at this point
f.flush()
# buffers are flushed to the file
f.write("this, too, is a test\n")
# again, line doesn't show in the file
f.close()
# closing the file flushes the buffers, text appears in file

根据文件.写入公司名称:

Note that due to buffering, flush() or close() may be needed before the file on disk reflects the data written.

你的代码片段的缩进完全是一团糟,但是不管怎样:你的代码开头是:

for i in hd_com.comment_message[1:500]:
    fl=open('delete.txt','wb')

这意味着您将在每次迭代时重新打开该文件以进行写入,从而删除上一次迭代可能已写入的内容。在

相关问题 更多 >

    热门问题