admin管理员组

文章数量:1435859

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 This is related to buffering.file.read(3) reads at least 3 characters from the file, but returns only 3, leaving the rest in an internal buffer for future read 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 demonstrate qq 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 be 111qq2333, not 111qq222333.) – chepner Commented Nov 16, 2024 at 15:01
  • Issue a seek when switching between reads and writes. – Mark Tolonen Commented Nov 16, 2024 at 15:05
  • @SIGHUP I know and chepner already pointed that out. It’s just best practice to issue a seek between reads and writes. – Mark Tolonen Commented Nov 16, 2024 at 15:57
Add a comment  | 

1 Answer 1

Reset to default 0

Your 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

本文标签: pythonProblems with Reading and Writing Files in r ModeStack Overflow