开发者

simple python file writing question

开发者 https://www.devze.com 2023-02-02 05:03 出处:网络
I\'m learning Python, and have run into a bit of a problem. On my OSX in开发者_如何转开发stall of Python 3.1, this happens in the console:

I'm learning Python, and have run into a bit of a problem. On my OSX in开发者_如何转开发stall 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.


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.


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.


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消