Skip to content

Instantly share code, notes, and snippets.

@lucky-verma
Created August 2, 2022 08:33
Show Gist options
  • Save lucky-verma/477df38fdf9e6f0c0592a4e2f0436bc2 to your computer and use it in GitHub Desktop.
Save lucky-verma/477df38fdf9e6f0c0592a4e2f0436bc2 to your computer and use it in GitHub Desktop.
import os
# create a dictionary with file names as keys
# and for each file name the paths where they
# were found
file_paths = {}
for root, dirs, files in os.walk('.'):
for f in files:
if f.endswith('.txt'):
if f not in file_paths:
file_paths[f] = []
file_paths[f].append(root)
# for each file in the dictionary, concatenate
# the content of the files in each directory
# and write the merged content into a file
# with the same name at the top directory
for f, paths in file_paths.items():
txt = []
for p in paths:
with open(os.path.join(p, f)) as f2:
txt.append(f2.read())
with open(f, 'w') as f3:
f3.write(''.join(txt))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment