M S
M S

Reputation: 944

Concatenation of Text Files (.txt files) with list in python?

Suppose I am having two text files 1.txt and 2.txt

The content of 1.txt as:

['Hi', 'I', 'am']

and

The content of 2.txt as:

['a', 'boy']

How to join the same and write the same into a new file in time efficient manner, say 3.txt, which should look like this:

['Hi', 'I', 'am', 'a', 'boy']

I have tried:

import os

file_list = os.listdir("path")
with open('out.txt', 'a+') as outfile:
   for fname in file_list:
       with open(fname) as infile:
          outfile.write(infile.read())

Upvotes: 3

Views: 384

Answers (2)

Stef van der Zon
Stef van der Zon

Reputation: 629

You could try something like this:

inputText = []
for file in ['1.txt','2.txt']:
    with open(file,'r') as file:
        inputText.extend(file.readlines()+['\n'])
with open ('3.txt','w') as output:
    for line in inputText:
        output.write(line)

or

with open ('3.txt','w') as output:
    for file in ['1.txt','2.txt']:
        with open(file,'r') as file:
            for line in file:
                output.write(line)
            output.write('\n')

Edited to your comment:

import re
inputList = []
for file in ['1.txt','2.txt']:
    with open(file,'r') as infile:
        for line in infile:
            inputList.extend(re.sub('[^A-Za-z0-9,]+', '', line).split(","))
print(inputList)
with open('3.txt','w') as outfile:
    for line in inputList:
        outfile.write(line + '\n')

Upvotes: 1

iElden
iElden

Reputation: 1280

You can use json module for loading json from file, so you will have a list insead of a string.
You just have to concatenate list using + operator and save it:

import json

final_result = []
for file in ["1.txt", "2.txt"]:
    with open(file, 'r') as fd:
        final_result += json.load(fd)

with open("3.txt", 'w') as fd:
    json.dump(final_result, fd)

Upvotes: 1

Related Questions