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.
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
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With