python - 包含列表列表的文本文件的串联?

标签 python python-3.x list file

假设我有两个文本文件 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/

相关文章:

Python 和 PGP/加密

Python 字符串操作

python - Scrapy,无法抓取任何页面: "TCP connection timed out: 110: Connection timed out."

python - 如何制作matplotlib下标和特殊字符?

python - 使用 matplotlib 创建全天空投影的好奇(坏?)行为

python - 如何将字典键值对转换为元组

sql-server - 使用 pyspark 对 SQL Server JDBC 使用 Windows 身份验证

c# - 列表到datagridView数据源

python - 使用 Python 3 上的任何数据结构检查一个组是否是其他组的子组的最有效方法

list - Prolog: between/3 最后有一个列表