替换文本文件中的特定行

1 投票
1 回答
1043 浏览
提问于 2025-04-17 16:07

我需要写一段代码,在Windows上运行一个叫做 foil2w.exe 的程序,这个程序可以进行一些关于机翼的空气动力学计算。这个 exe 文件需要一个输入文本文件(dfile_bl),里面有很多变量。每次运行后,我都得打开这个文件,把一个值(迎角)从0改到16,然后再运行一次。程序还会生成一个输出文件,叫做 aerola.dat,我需要保存里面最后一行的数据,因为那一行是结果。 我想做的是把这个过程自动化,也就是运行程序、保存结果、修改迎角然后再运行一次。我之前在Linux上做过这个,使用了 sed 命令来找到并替换迎角的那一行。现在我需要在Windows上实现这个,但我不知道从哪里开始。我在Linux上写的代码可以正常工作:

import subprocess
import os

input_file = 'dfile_bl'
output_file = 'aerloa.dat'
results_file = 'results.txt'

try:
    os.remove(output_file)
    os.remove(results_file)
except OSError:
    pass

for i in [0, 2, 4, 6, 8, 10, 12, 14, 16]:
    subprocess.call('./exe', shell=True)
    f = open(output_file, 'r').readlines()[-1]
    r = open(results_file, 'a')
    r.write(f)
    r.close()
    subprocess.call('sed -i "s/%s.00       ! ANGL/%s.00       ! ANGL/g" %s' % (i, i+2, input_file), shell=True)

subprocess.call('sed -i "s/18.00       ! ANGL/0.00       ! ANGL/g" %s' % input_file, shell=True)   

这个dfile文件看起来是这样的:

3.0          ! IFOIL
n2412aN    
0.00       ! ANGL
1.0        ! UINF 
300        ! NTIMEM

编辑: 现在运行得很好

import subprocess
import os
import platform

input_file = 'dfile_bl'
output_file = 'aerloa.dat'
results_file = 'results.txt'
OS = platform.system()
if OS == 'Windows':
    exe = 'foil2w.exe'
elif OS == 'Linux':
    exe = './exe'

try:
    os.remove(output_file)
    os.remove(results_file)
except OSError:
    pass

for i in [0, 2, 4, 6, 8, 10, 12, 14, 16]:
    subprocess.call(exe, shell=OS == 'Linux')
    f = open(output_file, 'r').readlines()[-1]
    r = open(results_file, 'a')
    r.write(f)
    r.close()
    s = open(input_file).read()
    s = s.replace('%s.00       ! ANGL' % str(i), '%s.00       ! ANGL' % str(i+2))
    s2 = open(input_file, 'w')
    s2.write(s)
    s2.close()
# Volver el angulo de dfile_bl a 0
s = open(input_file).read()
s = s.replace('%s.00       ! ANGL' % str(i+2), '0.00       ! ANGL')
s2 = open(input_file, 'w')
s2.write(s)
s2.close()
b

1 个回答

0

你能不能把

subprocess.call('sed -i "s/%s.00       ! ANGL/%s.00       ! ANGL/g" %s' % (i, i+2, input_file), shell=True)

换成类似这样的东西,

with open('input_file', 'r') as input_file_o:
    for line in input_file_o.readlines():
        outputline = line.replace('%s.00       ! ANGL' % i, '%s.00       ! ANGL' % i+2)

[1] http://docs.python.org/2/library/stdtypes.html#str.replace

撰写回答