Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
181 views
in Technique[技术] by (71.8m points)

python - How to write at a particular position in text file without erasing original contents?

I've written a code in Python that goes through the file, extracts all numbers, adds them up. I have to now write the 'total' (an integer) at a particular spot in the file that says something something something...Total: __00__ something something.

I have to write the total that I have calculated exactly after the Total: __ part which would mean the resulting line would change to, for example: something something something...Total: __35__ something something.

So far I have this for the write part:

import re
f1 = open("filename.txt", 'r+')
for line in f1:
    if '__' in line and 'Total:' in line:
        location = re.search(r'__', line)
print(location)

This prints out: <_sre.SRE_Match object; span=(21, 23), match='__'>

So it finds the '__' at position 21 to 23, which means I want to insert the total at position 24. I know I have to somehow use the seek() method to do this. But I have tried and failed several times. Any suggestions would be appreciated.

Important: The original contents of the file are to be preserved as it is. Only the total changes -- nothing else.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If the file is not particularly large, you can read its contents in memory as a string (or a list of lines), do the replacement and write the contents back. Something like this:

total = 'Total: __{}__'.format(12345)

with open(filename, 'r+') as f:
    contents = f.read().replace('Total: __00__', total)
    f.seek(0)
    f.truncate()
    f.write(contents)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...