Search This Blog

Saturday 16 January 2021

Python concatenate text files

 If you, like me, had to extract logs in the form of multiple files and then extract specific information out of it then the below python script will show you how to read text files from a folder, open each file one by one then saving the contents to a new concatenated file containing all of the contents from all the text files.


from os import walk
f = []
for (dirpath, dirnames, filenames) in walk("acslogs"):
    f.extend(filenames)
    break
print(f)
with open("acs-logs-concatenated.txt""w"as outfile:
    for fname in f:
        with open("acslogs/" + fname) as infile:
            for line in infile:
                outfile.write(line)

No comments:

Post a Comment

Nornir Compliance Check