0

I'm trying to append only after certain sections in this file I would like the be able to find the specific section by string value then add to it.

\\ desk



\\ phone



\\ chairs



\\tv

so that it looks like so

\\desk    # CODE finds '\\desk' then appends below it or above
wood
metal
etc

\\phone   # CODE finds '\\phone' then appends below it or above
cell
landline 
etc

\\chairs

\\tv

I know the solution is probably insanely easy and I swear I've done it before but apparently I have been asking google/the rest of the internet the wrong question.

if more clarification is needed basically i have a function that takes in args that will append certain sections based on what was selected and it has to run multiple times so I believe that appending is the way to go.

busta
  • 3
  • 3
  • does it answer your question ? https://stackoverflow.com/questions/10507230/insert-line-at-middle-of-file-with-python – rrrttt Feb 03 '20 at 19:16

1 Answers1

0

Try this:

def append(filename, **args):
    with open(filename) as f:
        text = [x for x in f.read().splitlines() if x]

    for k, v in args.items():
        k = r"\\ "+k
        if k not in text:
            continue

        i = text.index(k)
        for n in reversed(v):
            text.insert(i+1, n)

    return "\n".join(text)

print(append(
    "file.txt",
    desk=["wood", "metal", "etc"],
    phone=["cell", "landline", "etc"]
))

Output:

\\ desk
wood
metal
etc
\\ phone
cell
landline
etc
\\ chairs
\\tv

Hope this helps :)

Ed Ward
  • 2,333
  • 2
  • 10
  • 16
  • Yes this worked out amazingly just needed to tweak it a bit to fit le code and perfection. Even though I did not intend to pass list I like the extra mile you went ! Thank you for your quick response too ! – busta Feb 05 '20 at 12:13