Skip to content

Instantly share code, notes, and snippets.

@me-suzy
Last active September 26, 2022 08:32
Show Gist options
  • Save me-suzy/ca8b34049593e7d551c72bd41207c39d to your computer and use it in GitHub Desktop.
Save me-suzy/ca8b34049593e7d551c72bd41207c39d to your computer and use it in GitHub Desktop.
Merging text files / How do I concatenate text files in Python?
import shutil
import os
import glob
filenames = glob.glob('*.txt')
with open('output_file.txt','wb') as wfd:
for f in filenames:
with open(f,'rb') as fd:
shutil.copyfileobj(fd, wfd)
import fileinput
import glob
import os
import re
def read_files(file_path):
with open(file_path, encoding='utf8') as f:
text = f.read()
return text
def read_files(text, file_path):
with open(file_path, 'rb') as f:
f.write(text.encode('utf8', 'ignore'))
read_files = sorted(glob.glob("c:\\Folder6\\translated\\*.txt"))
with open("c:\\Folder6\\translated\\merged.txt", "wb") as outfile:
for f in read_files:
with open(f, "rb") as infile:
outfile.write(infile.read())
outfile.write(b"\n\n")
fileinput.close()
print(f)
import glob2
filenames = glob2.glob('*.txt') # list of all .txt files in the directory
with open('outfile.txt', 'w') as f:
for file in filenames:
with open(file) as infile:
f.write(infile.read()+'\n')
@me-suzy
Copy link
Author

me-suzy commented Aug 29, 2022

import fileinput
import glob
with open('c:\\Folder6\\merged.txt', 'w') as f:
    for line in fileinput.input(glob.glob('c:\\Folder6\\*.txt')):
        f.write(line)
    fileinput.close()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment