gpt4 book ai didi

python-3.x - 如何更改文本文件中的特定值?

转载 作者:行者123 更新时间:2023-12-01 03:19:14 25 4
gpt4 key购买 nike

我有两个数据文件(Amin 文件和 Volume 文件)。表格第一个想找出字符串“Amin”前面的数字。然后我想打开第二个文件并检查所有卷号,如果它们小于 Amin,则将该特定数字更改为 Amin。

Amin 文件如下所示:

 GP_DEF  1 4 "Zeitintervall Q_Strg [s]" 2 9.00000000e+002 0.00000000e+000  1
GP_DEF 1 5 "Hmin [m]" 2 1.00000000e-002 0.00000000e+000 1.79769313e+308
GP_DEF 1 6 "VELMAX [m/s]" 2 1.50000000e+001 0.00000000e+000 1
GP_DEF 1 7 "Amin" 2 0.5 0.5 0.5

卷文件如下所示:
SCALAR
ND 6813
ST 0
TS 0.0
0.207
0.313
0.423
0.595
0.930
0.714
0.590
0.1
1.652

结果应如下所示:
SCALAR
ND 6813
ST 0
TS 0.0
0.5
0.5
0.5
0.595
0.930
0.714
0.590
0.5
1.652

我写的代码不是以 Pythonic 的方式写的,但从逻辑上讲应该可以工作。但它不会产生结果。我的代码如下:
with open("VOLUMEN.dat") as f1, open('V_korr.dat', 'w') as out:
mylist = f1.read().splitlines()[0:4]
print(mylist)
for item in mylist:
out.write("%s\n" % item)

with open('hydro_as-2d.2dm', 'r') as f, open('Amin.txt', 'a') as outfile:
for line in f:
if line.startswith('GP_DEF 1 7 "Amin" '):
try:
line = line.strip()
columns = line.split()
Amin = float(columns[4])
print("{:.2f}".format(Amin), file=outfile)
except ValueError:
pass

with open("VOLUMEN.dat") as f1, open('V_korr.dat', 'w') as out:
for line in f1:
if line.startswith('GP_DEF 1 7 "Amin" '):
try:
line = line.strip()
columns = line.split()
Vol = float(columns[0])
if (V<Amin):
print("{:.2f}".format(Amin), file=outfile)
else :
print(line,file=outfile)
except ValueError:
pass

请给个提示,我在哪里做错了?谢谢!

最佳答案

我不会尝试解开您的代码,而是尝试为您有些不清楚的问题提供一个临时解决方案。这是我的建议:

#! /usr/bin/env python
#


def find_amin(fname, pattern, idx=5, default=None):
"""Locate first matching line in fname and return field at offset idx

If pattern is not found return default value.
"""
with open(fname) as fd:
for line in fd:
if line.startswith(pattern):
return line.split()[idx]
else:
return default


def adjust_volume_file(fname, limit, skip=3, indent=3):
"""Return lines in fname as a list adjusting data smaller than limit

Do not change the first skip lines. Adjusted numbers are output
with a margin of indent spaces.
"""
margin = indent * " "
result = []
with open(fname) as fd:
for idx, line in enumerate(fd):
if idx > skip:
result.append(margin + str(max(float(line), limit)) + '\n')
else:
result.append(line)
return result


if __name__ == "__main__":
amin = float(find_amin('amin-file.txt', ' GP_DEF 1 7 "Amin"'))

adjusted_data = adjust_volume_file('VOLUMEN.dat', amin)

with open('V_korr.dat', 'w') as fd:
fd.writelines(adjusted_data)

关于python-3.x - 如何更改文本文件中的特定值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47098431/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com