oldnoob
oldnoob

Reputation: 123

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?

Upvotes: 1

Views: 916

Answers (2)

Manish Gill
Manish Gill

Reputation: 98

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.

Upvotes: 1

Sufian Latif
Sufian Latif

Reputation: 13356

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 (e.g. due to exceptions).

Upvotes: 3

Related Questions