如何将大文本文件的每两行合并到Python列表中?

2024-03-29 04:49:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个.txt文件,分为多行,但每两行我想合并成一个列表中的一行。我该怎么做?你知道吗

非常感谢!你知道吗

我的组织是这样的:

[1 2 3 4

5 6]

[1 2 3 4

5 6 ]

而我需要的是:

[1 2 3 4 5 6]

[1 2 3 4 5 6]

Tags: 文件txt列表
3条回答

试试这个

final_data = []
with open('file.txt') as a:
    fdata= a.readlines()
    for ln in range(0,len(fdata),2):
        final_data.append(" ".join([fdata[ln].strip('\n'), fdata[ln+1].strip('\n')]))

print (final_data)

我觉得你可以用正则表达式来解决这个问题:

#! /usr/bin/env python2.7
import re

with open("textfilename.txt") as r:
     text_data = r.read()
independent_lists = re.findall(r"\[(.+?)\]",r ,re.DOTALL)
#now that we have got each independent_list we can next work on
#turning it into a list
final_list_of_objects = [each_string.replace("\n"," ").split() for each_string in independent_lists]
print final_list_of_objects

但是,如果不希望将它们作为列表对象,而只希望结果中列表之间没有换行符,则:

#! /usr/bin/env python2.7
import re

with open("textfilename.txt") as r:
     text_data = r.read()
new_txt = ""
for each_char in text_data:
     if each_char == "[":
        bool_char = True
     elif each_char == "]":
        bool_char = False
     elif each_char == "\n" and bool_char:
        each_char = " "
     new_txt += each_char
new_txt = re.sub(r"\s+", " ", new_txt) # to remove multiple space lines between numbers
data =[]
with open(r'<add file path here >','r') as file:
    x = file.readlines()

    for i in range(0,len(x),2):
        data.append(x[i:i+2])
new =[' '.join(i) for  i in data]
for i in range(len(new)):
    new[i]=new[i].replace('\n','')
new_file_name = r'' #give new file path here
with open(new_file_name,'w+') as file:
    for i in new:
        file.write(i+'\n')

相关问题 更多 >