Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concatenation of text files consisting list of lists?

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.

like image 665
M S Avatar asked Dec 18 '22 19:12

M S


2 Answers

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:

  • eval()
  • json
like image 60
Pedro Lobito Avatar answered Dec 29 '22 10:12

Pedro Lobito


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()
like image 24
Venkatachalam Avatar answered Dec 29 '22 12:12

Venkatachalam