Merge content of textfile to every file in folder

Question:

I want to modify several text-files within a folder.
I have the following code:

if command == "deployf":
    for root, dirs, files in os.walk(all_posts, topdown = False):
        for name in files:
            if name.endswith(".html"):
                file_name = os.path.join(root, name)
                with open(file_name, 'r+') as fp:
                    lines = fp.readlines()
                    fp.seek(0)
                    fp.truncate()
                    fp.writelines(lines[:-9])
    print('deployed to all files')

This deletes the last 9 lines in every html file in a folder. Now I want to merge (or append) the content of another .html file to the end of every file in the folder but I don`t know how.

Asked By: 0x01_PH

||

Answers:

You can ask for the path to the HTML file outside your loop:

path = input("Enter HTML File path to append to each file:")

Then read from the file:

root_content = open(path, 'r').readlines()

Then instead of removing the last 9 lines with fp.writelines(lines[:-9]), just write the root_content variable:

fp.writelines(root_content)

Im assuming this is what you want to do? You had all the knowledge shown in your problem to accomplish this, so please comment if i have misunderstood.

Answered By: TBCM

IIUC, you need to replace the last 9 lines of each (.html) with the content of your other file, right ?

If so, and to reduce visible noise, I would use Path.rglob from with slicing :

from pathlib import Path

if command == "deployf":
    all_posts = Path(all_posts)
    to_append = (all_posts / "the_other_file.html").read_text()
    
    for html in all_posts.rglob("*.html"):
        lines = html.read_text().splitlines()
        html.write_text("n".join(lines[:-9] + [to_append]))
    
    print("deployed to all files")

If you need to replace a slice in the middle (e.g 5:10) of each (.html), use this :

        lines = html.read_text().splitlines()
        lines = lines[:4] + [to_append] + lines[10:]
        html.write_text("n".join(lines))
Answered By: Timeless
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.