假设我有两个文本文件 1.txt 和 2.txt
1.txt
的内容为:
[['Hi', 'I'], ['I'], ['_am']]
和
2.txt
的内容为:
[['_a', 'good'], ['boy']]
如何以高效的方式加入相同的文件并将其写入新文件,例如 3.txt
,它应该如下所示:
[['Hi', 'I'], ['I'], ['_am'], ['_a', 'good'], ['boy']]
注意:我希望特殊字符(_)保持原样。
我已经尝试过在 Concatenation of Text Files (.txt files) with list in python? 中提到的堆栈溢出的先前答案。
我试过的是这样的:
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()
但我没有得到如上所示的所需输出。我现在得到的输出如下:
["[['Hi', 'I'], ['I'], ['_am']]", "[['_a', 'good'], ['boy']]"]
为什么我的当前输出多了一个("")
请提出一些有成效的建议?
提前致谢。
最佳答案
您可能想使用:
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"]]]
注意事项:
关于python - 包含列表列表的文本文件的串联?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53765829/