从Python中的文本文件中提取数据并写入新文件

时间:2014-02-13 14:07:26

标签: python python-3.x

我有一个类似下面给出的文件,我正在寻找一种方法来读出所有值,并使用Python将它们写入一个新文件。

Contact Angle (deg)     87.98
Wetting Tension (dy/cm)     2.576
Wetting Tension Left (dy/cm)    39.44
Wetting Tension Right (dy/cm)   39.44
Base Tilt Angle (deg)       0.00
Base (mm)           1.2414
Base Area (mm2)         1.2103
Height (mm)         0.5992
Tip Width (mm)          0.9480
Wetted Tip Width (mm)       0.9323
Sessile Volume (ul)     0.4752
Sessile Surface Area (mm2)  2.3382
Contrast (cts)          179
Sharpness (cts)         82
Black Peak (cts)        12
White Peak (cts)        191
Edge Threshold (cts)        86
Base Left X (mm)        3.592
Base Right X (mm)       4.835
Base Y (mm)         3.083
RMS Fit Error (mm)      4.248E-3

标题之间的间距(例如,接触角(度))和值是标签和空格的混合。我正在寻找一种获取以下格式的输出文件的方法:

87.98
2.576
39.44
39.44
0
1.2414
1.2103
0.5992
0.948
0.9323
0.4752
2.3382
179
82
12
191
86
3.592
4.835
3.083
4.25E-03

自从我使用Python以来,已经有一段时间了,甚至看到类似的问题,我已经碰壁了,似乎无法找到答案(我知道这是微不足道的。)

任何人都可以帮助我吗?

3 个答案:

答案 0 :(得分:1)

这有效:

# with block auto closes the files after the statements in it execute. It's good practice
with open(yourFile) as f, open(newFile, 'w') as f2:
    for line in f:
        line_out = line.split()[-1].strip()
        f2.write(line_out + '\n')

答案 1 :(得分:1)

我已经在问题中的示例数据上对此进行了测试,但它确实有效。

infile = open('file.txt', 'r')
outfile = open('outfile.txt', 'w')
for l in infile:
    outfile.write(l.split()[-1] + '\n')

infile.close()
outfile.close()

答案 2 :(得分:0)

answer = map(lambda a: a.strip().split()[-1], infile.readlines())

一行!好吧,不完全是一行。上面的一行假设您使用infile打开了infile = open("in.txt")。然后你必须将它写入out文件,例如out = open("out.txt", "w"); out.writelines(answer)

详细信息:

  1. a.strip().split()[-1]用空格(制表符/空格等)拆分每一行并从每行中取出最后一个元素(数字)
  2. map(lambda...部分将此应用于文件的每一行
相关问题