python - Problems with Reading and Writing Files in r+ Mode - Stack Overflow

I have a file named import_.text,the content is:111222333Then I have a file named file_open.py,the co

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

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745655963a4638543.html

相关推荐

  • python - Problems with Reading and Writing Files in r+ Mode - Stack Overflow

    I have a file named import_.text,the content is:111222333Then I have a file named file_open.py,the co

    12小时前
    30

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信