Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

combine multiple text files into one text file using python [duplicate]

Tags:

python

People also ask

How do I combine text files?

Two quick options for combining text files.Open the two files you want to merge. Select all text (Command+A/Ctrl+A) from one document, then paste it into the new document (Command+V/Ctrl+V). Repeat steps for the second document. This will finish combining the text of both documents into one.


You can read the content of each file directly into the write method of the output file handle like this:

import glob

read_files = glob.glob("*.txt")

with open("result.txt", "wb") as outfile:
    for f in read_files:
        with open(f, "rb") as infile:
            outfile.write(infile.read())

The fileinput module is designed perfectly for this use case.

import fileinput
import glob

file_list = glob.glob("*.txt")

with open('result.txt', 'w') as file:
    input_lines = fileinput.input(file_list)
    file.writelines(input_lines)

You could try something like this:

import glob
files = glob.glob( '*.txt' )

with open( 'result.txt', 'w' ) as result:
    for file_ in files:
        for line in open( file_, 'r' ):
            result.write( line )

Should be straight forward to read.


It is also possible to combine files by incorporating OS commands. Example:

import os
import subprocess
subprocess.call("cat *.csv > /path/outputs.csv")