在python中每隔x行反转文本块

时间:2017-08-14 14:17:02

标签: python numpy readlines

我确定这是一个简单的readlines解决方案。我花了一些时间试图解决它而没有成功。

我有一段文字,内容如下:

"This is the text 1"
0.0 2.0 2.0 2.0    
0.0 0.0 4.0 0.0    
0.0 0.0 0.0 0.0    
0.0 0.0 0.0 0.0    
0.0 0.0 0.0 0.0    
0.0 0.0 0.0 0.0
"This is the text 2"
0.0 5.0 3.0 5.0    
0.0 0.0 6.0 0.0    
0.0 0.0 0.0 0.0    
0.0 0.0 0.0 0.0    
0.0 0.0 0.0 0.0    
0.0 0.0 0.0 0.0

我正努力将其改为:

"This is the text 1"
0.0 0.0 0.0 0.0    
0.0 0.0 0.0 0.0    
0.0 0.0 0.0 0.0    
0.0 0.0 0.0 0.0    
0.0 0.0 4.0 0.0    
0.0 2.0 2.0 2.0
"This is the text 2"
0.0 0.0 0.0 0.0    
0.0 0.0 0.0 0.0    
0.0 0.0 0.0 0.0    
0.0 0.0 0.0 0.0    
0.0 0.0 6.0 0.0    
0.0 5.0 3.0 5.0

任何帮助非常感谢。 感谢

代码:

f = open("file.txt", "rb")
    s = f.readlines()
    f.close()
    f = open("newtext.txt", "wb")
    f.writelines(s[::-1])
    f.close()

返回整个txt文件。

1 个答案:

答案 0 :(得分:0)

这是在假设文本之间的行数始终一致的情况下工作的。

# Open file, split on newlines into a list
with open('file.txt') as f:
    data = f.read().splitlines()
# Break list into multiple lists 7 items long
# this covers the text and the 6 sets of numbers that follow
newlist = [data[i:i + 7] for i in range(0, len(data), 7)]

output = []
# Append the text, then iterate backwards across each list, stopping short of the text
for item in newlist:
    output.append(item[0])
    for x in item[:0:-1]:
        output.append(x)
# output to text file, adding a newline character at the end of each row
with open('newtext.txt', 'w') as f:
    for item in output:
        f.write('{}\n'.format(item))