Aaron Yodaiken
Aaron Yodaiken

Reputation: 19551

simple python file writing question

I'm learning Python, and have run into a bit of a problem. On my OSX install of Python 3.1, this happens in the console:

>>> filename = "test"
>>> reader = open(filename, 'r')
>>> writer = open(filename, 'w')
>>> reader.read()
''
>>> writer.write("hello world\n")
12
>>> reader.read()
''

And calling more test in BASH confirms that there is nothing in test. What's going on?

Thanks.

Upvotes: 2

Views: 452

Answers (4)

Greg Hewgill
Greg Hewgill

Reputation: 992857

There are two potential reasons why you are seeing this behaviour.

When you open a file for writing (with the "w" open mode in Python), the OS removes the original file and creates a totally new one. So by opening the file for reading first and then writing, the original reading handle refers to a file that no longer has a name (the file still exists until you close it). At that point you're reading from a different file than you're writing to.

After you swap the order of opening so you open for writing and then reading, you won't necessarily be able to read the data from the file until you flush it:

>>> writer.flush()
>>> reader.read()
'hello world\n'

Flushing the file writes any data that might be in Python's file buffers to the OS, so that when you read from the file from the other handle, the OS will return the data. Note that Python itself doesn't know these two handles refer to the same file, but the OS does.

Upvotes: 3

winwaed
winwaed

Reputation: 7801

And with the buttering, you will need to force the buffer to be emptied before reading. Closing the file is a good way to do this.

Upvotes: 0

Keith
Keith

Reputation: 43024

Buffering. If you really want to read and write to the same file open one handle using "w+".

Upvotes: 0

Falmarri
Falmarri

Reputation: 48569

You're probably trashing your file. It's not usually a good idea to open a file for reading and writing at the same time.

Upvotes: 1

Related Questions