3

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())
Rakesh
  • 81,458
  • 17
  • 76
  • 113
M S
  • 894
  • 1
  • 13
  • 41

2 Answers2

1

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)
iElden
  • 1,272
  • 1
  • 13
  • 26
  • Thanks Elden!. I tried your suggestion. How to specify the CWD path! – M S Dec 12 '18 at 09:47
  • By default, Python use your current working dir. If you want use specific path, you can add a path before the `file` variable : ``with open(path + file, 'r') as fd:``. If you want use the folder where your script are, you can use ``path = os.path.dirname(os.path.realpath(__file__))`` – iElden Dec 12 '18 at 09:54
1

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')
Stef van der Zon
  • 633
  • 4
  • 13
  • Thanks Van! How to specify the output in single list like `['Hi', 'I', 'am', 'a', 'boy']`. The output yielded from your suggestion results in separated lists like ['Hi', 'I', 'am',] and ['a', 'boy'] – M S Dec 12 '18 at 10:09
  • Thanks @Van. Your edited answer yields the output in one list like: `["['Hi', 'I', 'am']", "['a', 'boy']"]`. What I need the output to be displayed in a single list not list of lists. The desired output should be in somewhat this format: `['Hi', 'I', 'am', 'a', 'boy']`. – M S Dec 12 '18 at 12:53
  • Tested it on both python 2 & 3. Hope it does what you want now. 'inputList' in the third codeshippet should be the list you want. – Stef van der Zon Dec 12 '18 at 13:00
  • Sorry. I am getting the output as per your suggestion using `codeshippet -3` as `["['Hi', 'I', 'am']", "['a', 'boy']"]`. But, I want the output as: `['Hi', 'I', 'am', 'a', 'boy']`. There should not be any intermediate lists in between. All the strings should be clubbed into a single list. – M S Dec 12 '18 at 13:20
  • How does your txt file look, is it a single lined sentence which you want to split in words? Or is it multilined? – Stef van der Zon Dec 12 '18 at 13:29
  • The content of txt file is shown above. It's exactly the same. – M S Dec 12 '18 at 13:31
  • 1
    My bad, I thought you read in a multilined text and the text above was your list in python. Ill edit my code. I used some string editing to make it a python list like you want, but it's often easier to just save it as plain text in the txt file, and it will turn into a python list when you read it in. – Stef van der Zon Dec 12 '18 at 13:38
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/185151/discussion-between-m-s-and-van-der-zon-stef). – M S Dec 12 '18 at 14:41
  • Thanks. It worked. But does there exist any way apart from using `re` ? – M S Dec 12 '18 at 14:43