Skip to content

Instantly share code, notes, and snippets.



Last active Apr 29, 2017
What would you like to do?
#!/usr/bin/env python
Merge/Join/Combine lines of multiple input files.
Write lines consisting of the sequentially corresponding lines from each input file, separated by space character, to output file.
TODO: implements params like
import sys
from contextlib import ExitStack
from itertools import zip_longest
def main(args):
if len(args) < 3:
print(sys.argv[0] + ' <input-file-1> <input-file-2> [<input-file-n>...] <output-file>')
mergeFiles(args[:len(args)-1], args[len(args)-1])
def mergeFiles(inputFileNames, outputFileName, delimiterChar=" ", fillValue="-"):
with ExitStack() as eStack:
inputFiles = [eStack.enter_context(open(fileName, 'r', encoding='utf-8', errors='replace')) for fileName in inputFileNames]
with open(outputFileName, 'w', encoding='utf-8', errors='replace') as outputFile:
for tupleOfLineFiles in zip_longest(*inputFiles, fillvalue=fillValue):
outputFile.write(delimiterChar.join(map(str.strip, tupleOfLineFiles)) + "\n")
if __name__ == "__main__":
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment