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?

4
  • 2
    Why are you flushing stdout, and not closing the file object? Commented Feb 14, 2014 at 12:59
  • Sorry. It was a mistake Commented Feb 14, 2014 at 13:01
  • 2
    And why did you name the outputfile inputfile? Commented Feb 14, 2014 at 13:01
  • Is it a script, or you are trying in python shell? If it is a script, the file should be closed automatically on exit, so that shouldn't be the issue Commented Feb 14, 2014 at 13:02

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

5 Comments

Shouldn't the file be closed (and flushed) automatically on script exit ?
@SunnyNanda: Yes, the file would also be closed when Python exits. There is no mention of that in the question though. I also mention that the presumption is that argument is not an empty string.
@SunnyNanda: Added another assumption; that the OP is looking at the right file.
Thank you Martjin Pieters. Your second option worked!!
@user2599593: Then the first one would have worked too; all file.__exit__() does is call self.close(). file.__exit__() is called when the with block ends.
1

Try with

outfile.close()

note the brackets.

outfile.close

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

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.