Can't write data to file using python

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

      

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

+1


source to share


3 answers


You are not calling the method outfile.close

.

No need to hide here, just call close:

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

      



or better yet, use a file object as a context manager:

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

      

This is all assuming that argument

it is not an empty string and that you are looking at the correct file. If you use a relative path in inputfile

which absolute path is used depends on your current working directory and you can look at the wrong file to see if something was written in it.

+5


source


Try

outfile.close()

      

notice the parentheses.



outfile.close

      

will only return the object object and do nothing.

+1


source


You will not see the data that you entered into it until you close or close the file. And in your case, you will not clean / close 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()

      

0


source







All Articles