Skip to content

Instantly share code, notes, and snippets.

@lucky-verma
Created August 2, 2022 08:33
Show Gist options
  • Select an option

  • Save lucky-verma/477df38fdf9e6f0c0592a4e2f0436bc2 to your computer and use it in GitHub Desktop.

Select an option

Save lucky-verma/477df38fdf9e6f0c0592a4e2f0436bc2 to your computer and use it in GitHub Desktop.

Revisions

  1. lucky-verma created this gist Aug 2, 2022.
    24 changes: 24 additions & 0 deletions mergeTxtFilesInSubdirectory.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,24 @@
    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))