When I use this code,it will automatically creates a file.Why?Where can I see the source code of this function?
with open('E:/test.txt','w') as f:
for i in range(10):
f.write('abc\n')
f.close()
When I use this code,it will automatically creates a file.Why?Where can I see the source code of this function?
with open('E:/test.txt','w') as f:
for i in range(10):
f.write('abc\n')
f.close()
The w
flag opens a file, truncates it, and then begins writing from the beginning. I was interested in investigating why it creates files as soon as you call it, but there doesn't seem to be much in the spec that describes it's anticipated behavior.
While it mightn't be easy to find the source code, you can see the documentation here. See the table under the modes
argument for an explanation of all the modes you can use.
We can only guess as to the intentions of the people who wrote open()
, but it would seem that the one thing consistent among all modes is:
Open file and return a corresponding file object. If the file cannot be opened, an OSError is raised.
Without getting input from whoever wrote the spec I would assume they consider "open file" to involve creating it if it doesn't exist.
This is actually a very good question, you got me thinking. Since Python is open-source, one should be able to see more than the documentation, the actual code! I utilized this thread and finally got to the source code. This sort of built-in functions are usually implemented in C. So if you know C -I don't!- you will be able to read through it and understand fully.
Here is the source code:
https://github.com/python/cpython/blob/master/Modules/_io/fileio.c
(Check out the full directory to make sense of it:
https://github.com/python/cpython/tree/master/Modules/_io)
Search the term 'w' (with the single quotes) and go from there.
It contains code like this, which is what you are looking for:
case 'r':
if (rwa)
goto bad_mode;
rwa = 1;
self->readable = 1;
break;
case 'w':
if (rwa)
goto bad_mode;
rwa = 1;
self->writable = 1;
flags |= O_CREAT | O_TRUNC;
break;