You can use the glob
package to get all the text files from a given folder. Then, iterate each file and gather the contents into a list. Finally, write the contents separated by a newline in the output file using the .join()
method of Python str
.
Here is an example:
from glob import glob
def main():
txt_files = glob("folder/*.txt")
contents = []
for file in txt_files:
with open(file) as f_in:
contents.append(f_in.read())
with open("out_file.txt", mode="w") as f_out:
f_out.write("\n".join(contents))
if __name__ == "__main__":
main()
If you have lots of files or/and the files are huge, consider using a lazy version to avoid saturating the RAM:
from glob import glob
def gen_contents(txt_files: list[str]):
for file in txt_files:
with open(file) as f_in:
yield from f_in.readlines()
yield "\n"
def main():
txt_files = glob("*.txt")
with open("result.txt", mode="w") as f_out:
contents = gen_contents(txt_files)
f_out.writelines(contents)
if __name__ == "__main__":
main()