Home > Software engineering >  Python Merging files after a name fragment
Python Merging files after a name fragment

Time:04-01

I have two folders when I have dynamic quantity files. For example: In folder "A" I've files:

FileName_1.txt
FileName_2.txt
FileName_3.txt

In folder "B" I've files:

NewFile_1.txt
NewFile_2.txt
NewFile_3.txt

The number of files in both folders will always be the same. Is there any simple way how to merge files by number in filename? As result I want to:

Data from file NewFile_1.txt add to FileName_1.txt
Data from file NewFile_2.txt add to FileName_2.txt, etc.

It doesn't have to be a solution to the problem. Thank you for the tips.

CodePudding user response:

Just something like this. Grab all the file names from the B directory, find the suffix (after the _), and open the A file based on that:

import os

newnames = [k for k in os.listdir( "B") if k[-4:] == '.txt']
for name in newnames:
    i = name.find('_')
    suffix = name[i:]
    olddata = open('B/'   name).read()
    open('A/FileName' suffix, 'a').write(olddata)
  • Related