1
outfile = open(inputfile, 'w')
outfile.write(argument)
outfile.flush()
os.fsync(outfile)
outfile.close

This is the code snippet. I am trying to write something into a file in python. but when we open the file, nothing is written into it. Am i doing anything wrong?

A R
  • 2,697
  • 3
  • 21
  • 38

3 Answers3

5

You are not calling the outfile.close method.

No need to flush here, just call close properly:

outfile = open(inputfile, 'w')
outfile.write(argument)
outfile.close()

or better still, use the file object as a context manager:

with open(inputfile, 'w') as outfile:
    outfile.write(argument)

This is all presuming that argument is not an empty string, and that you are looking at the right file. If you are using a relative path in inputfile what absolute path is used depends on your current working directory and you could be looking at the wrong file to see if something has been written to it.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
1

Try with

outfile.close()

note the brackets.

outfile.close

would only return the function-object and not really do anything.

sebastian
  • 9,526
  • 26
  • 54
0

You wont see the data you have written into it until you flush or close the file. And in your case, you are not flushing/closing the file properly.

* flush the file and not stdout - So you should invoke it as outfile.flush()
* close is a function. So you should invoke it as outfile.close()

So the correct snippet would be

  outfile = open(inputfile, 'w')
  outfile.write(argument)
  outfile.flush()
  outfile.close()
Prem Anand
  • 2,469
  • 16
  • 16