Created
August 2, 2022 08:33
-
-
Save lucky-verma/477df38fdf9e6f0c0592a4e2f0436bc2 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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