Last active
September 26, 2022 08:32
-
-
Save me-suzy/ca8b34049593e7d551c72bd41207c39d to your computer and use it in GitHub Desktop.
Merging text files / How do I concatenate text files in Python?
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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') |
Author
me-suzy
commented
Aug 29, 2022
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment