由列表列表组成的文本文件的串联?

时间:2018-12-13 16:06:57

标签: 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']]"]

为什么我的当前输出中有多余的(“”)。

请提出一些有益的建议?

谢谢。

6 个答案:

答案 0 :(得分:3)

您可能要使用:

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"]]]

注意:

答案 1 :(得分:2)

您的文件是否总是这样?然后,您只需删除“外部” []

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())

哪些印刷品

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

答案 2 :(得分: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']

答案 3 :(得分:2)

import ast
x="[['Hi', 'I'], ['I'], ['_am']]"
ast.literal_eval(x)

输出:

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

在您的情况下:

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()

答案 4 :(得分:1)

尝试一下(不要忘了加星号运算符):

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()

答案 5 :(得分:1)

想要真正的效率,把1.txt不带最后一个字符写到3.txt,再不带第一个字符写2.txt

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()

给予

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