I have a file named import_.text
,the content is:
111222333
Then I have a file named file_open.py
,the code is:
file = open("import\_.text", mode='r+')
print(file.read(3))
file.write("qq")
The result is 111222333qq.I'm curious why "qq" was added to the end of the file (111222333qq), instead of being added according to the pointer's position (111qq222333).Thanks for your answer.
I have a file named import_.text
,the content is:
111222333
Then I have a file named file_open.py
,the code is:
file = open("import\_.text", mode='r+')
print(file.read(3))
file.write("qq")
The result is 111222333qq.I'm curious why "qq" was added to the end of the file (111222333qq), instead of being added according to the pointer's position (111qq222333).Thanks for your answer.
Share Improve this question asked Nov 16, 2024 at 14:55 fang ddfang dd 11 3 |1 Answer
Reset to default 0Your required output looks like an insert rather than a replacement.
Thus, to achieve your objective you could do this:
pos = 3
with open("foo.txt", "r+") as file:
content = file.read() # consume entire contents of the file
output = content[:pos] + "qq" + content[pos:] # insert text at the relevant position
file.seek(0) # seek to BOF
file.write(output) # write the output
When the original file content is:
111222333
...this code will generate:
111qq222333
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745655963a4638543.html
file.read(3)
reads at least 3 characters from the file, but returns only 3, leaving the rest in an internal buffer for futureread
calls to consume.write
, however, ignores the buffer, and uses the pointer that indicates what has actually been read from disk. (A proper answer would show how to disable this buffering and demonstrateqq
being written where you expect it to go, though note that you cannot insert into the file, only overwrite the next 2 bytes. The resulting file would probably be111qq2333
, not111qq222333
.) – chepner Commented Nov 16, 2024 at 15:01