我有 .txt 檔案為:
x1 x2 x3 y1 y2 y3 z1 z2 z3
x1 x2 x3 y1 y2 y3 z1 z2 z3
例如 :
1.9849207e-01 1.9993099e-01 2.0150793e-01 9.6169322e-02 9.6354487e-02 1.0630896e-01 1.5000000e-02 1.6090730e-02 1.5000000e-02
1.9993099e-01 2.0261176e-01 2.0150793e-01 9.6354487e-02 1.0536750e-01 1.0630896e-01 1.6090730e-02 1.6090730e-02 1.5000000e-02
我使用了以下片段:
from itertools import *
with open('path/snip.txt', 'r') as f_input, open('path/snip_output.txt', 'w') as f_output:
values = []
for line in f_input:
values.extend(line.split())
ivalues = iter(values)
for triple in iter(lambda: list(islice(ivalues, 3)), []):
f_output.write(' '.join(triple) '\n')
并得到:
x1 x2 x3
y1 y2 y3
z1 z2 z3
x1 x2 x3
y1 y2 y3
z1 z2 z3
但是,這是我想要的,但我不知道如何處理 islice 中的兩個步驟:
x1 y1 z1
x2 y2 z2
x3 y3 z3
x1 y1 z1
x2 y2 z2
x3 y3 z3
uj5u.com熱心網友回復:
with open('path/snip.txt', 'r') as f_input, open('path/snip_output.txt', 'w') as f_output:
for line in f_input:
xyz = line.split()
x, y, z = xyz[0:3], xyz[3:6], xyz[6:9]
for triple in zip(x, y, z):
f_output.write(' '.join(triple) '\n')
寫
1.9849207e-01 9.6169322e-02 1.5000000e-02 1.9993099e-01 9.6354487e-02 1.6090730e-02 2.0150793e-01 1.0630896e-01 1.5000000e-02 1.9993099e-01 9.6354487e-02 1.6090730e-02 2.0261176e-01 1.0536750e-01 1.6090730e-02 2.0150793e-01 1.0630896e-01 1.5000000e-02
uj5u.com熱心網友回復:
你可以這樣做:
n = 3
values = []
with open("log.txt") as f, open("output.txt", 'w') as g:
for line in f:
lst = line.rstrip().split()
for i in zip(*[lst[i:i n] for i in range(0, len(lst), n)]):
print(*i, file=g)
內容output.txt:
1.9849207e-01 9.6169322e-02 1.5000000e-02
1.9993099e-01 9.6354487e-02 1.6090730e-02
2.0150793e-01 1.0630896e-01 1.5000000e-02
1.9993099e-01 9.6354487e-02 1.6090730e-02
2.0261176e-01 1.0536750e-01 1.6090730e-02
2.0150793e-01 1.0630896e-01 1.5000000e-02
您需要將回傳的串列從line.rstrip().split()in 拆分為n塊。然后,zip您可以并行遍歷它們。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/445438.html
標籤:Python python-3.x 文本文件
上一篇:根據位置在python中拆分陣列
