Concise way to write the same line in multiple files - Python

Viewed 386

I have several opened files. Now, I need to write the same line in all of them. My current code is the following, but it is unelegant and very repetitive. Is there a way of doing it in less lines?

with open("a.txt", "a+") as fa,\
     open("b.txt", "a+") as fb,\
     open("c.txt", "a+") as fc,\
     open("d.txt",  "a+") as fd,\
     open("e.txt", "a+") as fe,\
     open("f.txt", "a+") as ff,\
     open("g.txt", "a+") as fg:

    fa.write("header")
    fb.write("header")
    fc.write("header")
    fd.write("header")
    fe.write("header")
    ff.write("header")
    fg.write("header")

In the rest of the program (not shown), I deal with each file differently, appending different information to each of them.

If this post is duplicate, I am sorry!

3 Answers

simply use a for loop:

for file in files_list:
    with open(file, "a+") as fa:
        fa.write("header")

put all file names in files_list

You could create a context manager to create a dictionary of the opened files and then iterate through this dictionary to write the header in all of them.

A dictionary is used instead of a list to make sure you can use the files independently and reliably in the main code

A possible implementation:

from contextlib import contextmanager

@contextmanager
def open_many(key_path):
    opened_files = {}
    try:
        opened_files = {key: open(path, "w") for key, path in key_path.items()}
        yield opened_files
    finally:
        for f in opened_files.values():
            f.close()


with open_many({"a": "a.txt", "b": "b.txt"}) as file_map:
    for f in file_map.values():
        f.write("header")

The simplest I can figure is this:

for i in range(7):
    f[i] = open("f" + chr(ord('a') + i) + ".txt", "a+")

for i in range(7):
    f[i].write("header")

And then you can do your stuff...

Related