简体   繁体   English

数据未写入文件[Python]

[英]Data not getting written in file [Python]

final=open("war.txt","w+")
for line in madList:
  line=line.split('A ')
  dnsreg= line[1]
  print dnsreg
  final.write(dnsreg)

While printing dnsreg I can see the output, but when I write it to a file, nothing is being written. 在打印dnsreg我可以看到输出,但是当我将它写入文件时,没有任何内容被写入。 No syntax error is there either. 也没有语法错误。 Any idea? 任何想法?

The data written to a file is not written immediately, it's kept in a buffer, and large amounts are written at a time so save the writing-to-disk overhead. 写入文件的数据不会立即写入,而是保存在缓冲区中,并且一次写入大量数据,因此节省了写入磁盘的开销。 However, upon closing a file, all the buffered data is flushed to the disk. 但是,在关闭文件时,所有缓冲的数据都会刷新到磁盘。

So, you can do two things: 所以,你可以做两件事:

  1. Call final.close() when you are done, or 完成后调用final.close() ,或者
  2. Call final.flush() after final.write() if you don't want to close the file. 呼叫final.flush()final.write()如果你不想关闭文件。

Thanks to @Matt Tanenbaum, a really nice way to handle this in python is to do the writing inside a with block: 感谢@Matt Tanenbaum,在python中处理这个问题的一个非常好的方法是在with块中进行写入:

with open("war.txt","w+") as final:
    for line in madList:
        line=line.split('A ')
        dnsreg= line[1]
        print dnsreg
        final.write(dnsreg)

Doing this, you'll never have to worry about closing the file! 这样做,你永远不必担心关闭文件! But you may need to flush in case of premature termination of the program (eg due to exceptions). 但是,如果程序提前终止(例如由于例外),您可能需要刷新。

You should use the with statement in Python when using resources that have to be setup and tear down, like opening and closing of files. 在使用必须设置和拆除的资源(如打开和关闭文件)时,应该在Python中使用with语句。 Something like: 就像是:

with open("war.txt","w+") as myFile:
    for line in madList:
        line=line.split('A ')
        dnsreg= line[1]
        myFile.write(dnsreg)

If you do not want to use with , you will have to manually close the file. 如果你不希望使用with ,你必须手动关闭该文件。 In that case, you can use the try...finally blocks to handle this. 在这种情况下,您可以使用try...finally块来处理这个问题。

try:
    myFile = open("war.txt", "w+")
    for line in madList:
    line=line.split('A ')
    dnsreg= line[1]
    myFile.write(dnsreg)
finally:
    myFile.close()

finally will always work, so your file is closed, and changes are written. finally将始终有效,因此您的文件已关闭,并且已写入更改。

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

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