Python 替换文本文件中的特定行
我需要为Windows编写代码,运行exe调用Python 替换文本文件中的特定行,python,subprocess,Python,Subprocess,我需要为Windows编写代码,运行exe调用foil2w.exe,从机翼进行一些空气动力学计算。这个exe有一个包含许多变量的输入文本文件(dfile\u bl)。然后在每次跑步后,我必须打开它,将一个值(迎角)从0更改为16,然后再次跑步。还生成一个名为aerola.dat的输出文件,在该文件中,我必须保存最后一行,即包含结果的那一行。 我要做的是使过程自动化,运行程序,保存结果,改变角度,然后再次运行。我已经在Linux上完成了这项工作,并使用sed命令查找线并将其替换为角度。现在我必须为
foil2w.exe
,从机翼进行一些空气动力学计算。这个exe
有一个包含许多变量的输入文本文件(dfile\u 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)
该文件看起来像:
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
你不能换一个吗
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] 主动性很好,实现了自动化@uʍopǝpısdn,这是一个比-更好的问题,但仍需要从我的原始评论中澄清,以便更广泛地使用;)你能给我们看一下“dbfile_bl”的摘录吗?这可能有助于理解您试图做的事情。我尝试了您的解决方案,我得到了这个
回溯(最近一次调用):文件“run2.py”,第20行,输入文件中的行。readlines():AttributeError:'str'对象没有属性“readlines”
是的,输入文件
必须是文件对象,我没有使这个代码100%正确,只是给你一个想法。。。我将编辑示例以反映这一点……谢谢,现在我在连接str和int对象时遇到了一个错误,但我认为a现在可以解决它。谢谢,如果答案对你有帮助,请接受它,这样其他人就知道这个问题已经用建议的解决方案“解决”了。