简体   繁体   中英

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. 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
  2. Call final.flush() after final.write() if you don't want to close the file.

Thanks to @Matt Tanenbaum, a really nice way to handle this in python is to do the writing inside a with block:

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. 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. In that case, you can use the try...finally blocks to handle this.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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