4

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

The content of 1.txt as:

[['Hi', 'I'], ['I'], ['_am']]

and

The content of 2.txt as:

[['_a', 'good'], ['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'], ['I'], ['_am'], ['_a', 'good'], ['boy']]

Note: I want the special characters (_) to be remain as it is.

I have tried from a previous answer of stack overflow which is mentioned in Concatenation of Text Files (.txt files) with list in python?

What I have tried is as follows:

global inputList
inputList = []
path = "F:/Try/"
def load_data():
    for file in ['1.txt', '2.txt']:
        with open(path + file, 'r', encoding = 'utf-8) as infile:
           inputList.extend(infile.readlines())
    print(inputList)
load_data()

But I am not getting the desired output as shown in above. The output what I am getting right now is as follows:

["[['Hi', 'I'], ['I'], ['_am']]", "[['_a', 'good'], ['boy']]"]

Why there is a extra (" ") in the current output of mine.

Please suggest something productive?

Thanks in Advance.

finefoot
  • 9,914
  • 7
  • 59
  • 102
M S
  • 894
  • 1
  • 13
  • 41
  • 1
    You are trying to read an array from a file. But reading a file like this returns a string. You will have to parse the string convert it to an array. There are a lot of things going wrong here. – DollarAkshay Dec 13 '18 at 16:14

6 Answers6

3

You may want to use:

import json

with open("1.txt", "r") as t1, open("2.txt", "r") as t2, open("3.txt", "w") as t3:
    t3.write(json.dumps([eval(t1.read().strip()), eval(t2.read().strip())]))

3.txt

[[["Hi", "I"], ["I"], ["_am"]], [["_a", "good"], ["boy"]]]

Notes:

Pedro Lobito
  • 94,083
  • 31
  • 258
  • 268
  • 1
    Thanks Pedro. I am not that proficient in json. I will go through with your suggested links. Thanks a ton! – M S Dec 13 '18 at 16:59
2

Do your files always look like that? You can then just remove the "outer" [ and ].

path = "F:/Try/"

def load_data():
    result = []
    for file in ['1.txt', '2.txt']:
        with open(path + file, 'r', encoding='utf-8') as infile:
            result.append(infile.readline().strip()[1:-1])
    return "[" + ", ".join(result) + "]"

print(load_data())

Which prints

[['Hi', 'I'], ['I'], ['_am'], ['_a', 'good'], ['boy']]
finefoot
  • 9,914
  • 7
  • 59
  • 102
2
xlist = ["[['Hi', 'I'], ['I'], ['_am']]", "[['_a', 'good'], ['boy']]"]
ylist = []
for x in xlist:
    if x.startswith('[') and x.endswith(']'):
        ylist.append(x[1:-1])
zstring =''
for y in ylist:
    if zstring == '':
        zstring = y
    else:
        zstring += ', ' + y

print (zstring)
#['Hi', 'I'], ['I'], ['_am'], ['_a', 'good'], ['boy']
ycx
  • 3,155
  • 3
  • 14
  • 26
2
import ast
x="[['Hi', 'I'], ['I'], ['_am']]"
ast.literal_eval(x)

output:

[['Hi', 'I'], ['I'], ['_am']]

In your case:

import ast
global inputList
inputList = []
path = "F:/Try/"
def load_data():
    for file in ['1.txt', '2.txt']:
        with open(path + file, 'r', encoding = 'utf-8') as infile:
           inputList.extend(ast.literal_eval(infile.readlines()))
    print(inputList)
load_data()
Venkatachalam
  • 16,288
  • 9
  • 49
  • 77
1

Try this out (don't forget to put the star operator):

import ast
global inputList
inputList = []
path = "F:/Try/"
def load_data():
    for file in ['1.txt', '2.txt']:
        with open(path + file, 'r', encoding = 'utf-8') as infile:
            inputList.extend(ast.literal_eval(*infile.readlines()))
    print(inputList)
load_data()
Tan En De
  • 331
  • 1
  • 3
  • 13
1

If you want real efficiency, write 1.txt to 3.txt without the last character, and then write 2.txt without the first character

def concat1():

    with open('3.txt', 'w') as outf:
        with open('1.txt') as inf:
            outf.write(inf.read()[:-1])

        outf.write(',')

        with open('2.txt') as inf:
            outf.write(inf.read()[1:])
            
concat1()

gives

[['Hi', 'I'], ['I'], ['_am'],['_a', 'good'], ['boy']]
Subham
  • 397
  • 1
  • 6
  • 14