A R
A R

Reputation: 2803

Unable to write data into a file using python

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?

Upvotes: 1

Views: 1326

Answers (3)

Prem Anand
Prem Anand

Reputation: 2547

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()

Upvotes: 0

Martijn Pieters
Martijn Pieters

Reputation: 1124258

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.

Upvotes: 5

sebastian
sebastian

Reputation: 9696

Try with

outfile.close()

note the brackets.

outfile.close

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

Upvotes: 1

Related Questions