简体   繁体   中英

Rewrite a specific portion of a text file in python

(1) I am using Python and would like to create a function that rewrites a portion of a text file. Referencing the sample example below, I would like to be able to delete everything from [Variables] onwards and write new content from that position. I can't figure out how to achieve this using any of seek(), truncate() and/or tell().

I'm thinking I may have to read and store the file's contents up to [Variables] and write that back in before appending the new content. Is there a better way to go about this?

(2) Bonus question: How would I do this if there was content beyond the variables section that I wanted to remain unchanged? This is currently not required, but it would be helpful to know for the future.

Sample Text File:

"[Log]

This happened

That happened

etc

[Variables]

Animals: [Dog, Cat]

Number: 4"

You can try to use regex:

import re
string = text
word = '[Variables]'
# The Regex pattern to match al characters on and after '[Variables]'
pattern  = word + ".*"
# Remove all characters after '[Variables]' from string
string = re.sub(pattern, '', string)
print(string)

Here if the text is the text that you show on your question, the output of the code will be:

"[Log]

This happened

That happened

etc"

In order to add new text at the end you just need to concatenate a new string to the existing one like:

string += "Some Text"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM