读取文本文件并提取数据

时间:2016-11-07 09:21:48

标签: python python-2.7 python-3.x

我想在python中读取一个文本文件。该文件的数据如下所示:

O04444
(T2 D=12.7 CR=0. - ZMIN=-11.5 - flat end mill)
(T3 D=4.978 CR=0. TAPER=118deg - ZMIN=-22. - drill)
N10 G90 G94 G17
N15 G21
N20 G53 G0 Z0.

(Face2)
N30 T2 M6
N35 S1380 M3
N40 G54
N45 M8
N60 G0 X108.255 Y-46.214
N65 G43 Z15. H2
N70 T3
N75 G0 Z5.
N80 G1 Z-0.73 F355.6
N85 G18 G3 X106.985 Z-2. I-1.27 K0.
N90 G1 X100.
N95 X0.
N100 G17 G2 Y-36.199 I0. J5.008
N105 G1 X100.
N110 G3 Y-26.184 I0. J5.008
N115 G1 X0.
N120 G2 Y-16.168 I0. J5.008
N125 G1 X100.
N130 G3 Y-6.153 I0. J5.008
N135 G1 X0.
N140 G18 G3 X-1.27 Z-0.73 I0. K1.27
N145 G0 Z15.
N150 M5
N155 G53 G0 Z0.

(Drill3)
N165 M9
N170 M1
N175 T3 M6
N180 S5850 M3
N185 G54
N190 M8
N200 G17
N205 G0 X80. Y-40.
N210 G43 Z15. H3
N215 T2
N225 G0 Z5.
N230 G98 G81 X80. Y-40. Z-22. R3. F584.2
N235 Y-25.
N240 Y-10.
N245 G80
N250 G0 Z15.
N255 M5
N260 G53 G0 Z0.

(2D Pocket1)
N270 M9
N275 M1
N280 T2 M6
N285 S1380 M3
N290 G54
N295 M8
N310 G0 X47.315 Y7.644
N315 G43 Z15. H2

我想将此文件拆分为4个不同的文件。只要中间有空行,就应将它分开。我是python的新手。任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:0)

问题很简单。你可以拥有一个不断迭代文件中每一行的计数器。

i = 0
for line in open("somefile", "r"):
    if len(line.strip()) == 0:
        continue
    with open("new_file{}".format(i), "w") as new_file:
        new_file.write(line)
    i += 1

如果你想使用该语言的一些更高级的功能,你可以放弃使用的LOC并摆脱丑陋的if / else语句

lines = open("somefile", "r").readlines()
non_empty = [line for line in lines if len(line.strip()) != 0]
for i, line in enumerate(non_empty):
    with open("new file{}".format(i), "w") as new_file:
        new_file.write(line)

答案 1 :(得分:0)

您可以使用re立即拆分:

import re
for x in re.split('\n\n',open('bla.txt').read()):
    open(x.split("\n")[0].strip('()').replace(" ","_"),'w').write(x) 

x.split部分是根据标题确定文件名,您可以更改它。