从命令行读取(x,y)对流,并将修改后的对(x,f(y))写入fi

2024-10-01 22:33:08 发布

您现在位置:Python中文网/ 问答频道 /正文

问题是:

从命令行读取(x,y)对的流。 修改datatrans1.py脚本,使其从命令行读取(x,y)对流,并将修改后的对(x,f(y))写入文件。新脚本(此处称为datatrans1b.py)的用法如下:

这是命令行的输入:
python datatrans1b.py tmp.out 1.1 3 2.6 8.3 7-0.1675

产生输出文件tmp.out:

  • 1.1 1.20983e+01
  • 2.6 9.78918e+00
  • 70.00000e+00

提示:在for循环中运行sys.argv数组并使用range函数 具有适当的起始索引和增量 下面是datatrans1.py原始脚本:

```
import sys, math

try:
   infilename = sys.argv[1]
   outfilename = sys.argv[2]
except:
   print("Usage:", sys.argv[0], "infile outfile")
   sys.exit(1)

ifile = open(infilename, 'r')  # open file for reading
ofile = open(outfilename, 'w')  # open file for writing


def myfunc(y):
   if y >= 0.0:
       return y ** 5 * math.exp(-y)
   else:
       return 0.0

```

逐行读取ifile并写出转换后的值:

```

for line in ifile:
   pair = line.split()
   x = float(pair[0])
   y = float(pair[1])
   fy = myfunc(y)  # transform y value
   ofile.write('hello' '%g  %12.5e\n' % (x, fy))
ifile.close()
ofile.close()

```

关于如何修改上述代码以正确运行命令行参数并生成带有坐标对的tmp.out文件的任何线索都将非常有用


Tags: 文件命令行py脚本forsysopenout
1条回答
网友
1楼 · 发布于 2024-10-01 22:33:08

这应该可以解决问题:

import sys, math

try:
   outfilename = sys.argv[1]
except:
   print("Usage:", sys.argv[0], "outfile pairs")
   sys.exit(1)

ofile = open(outfilename, 'w')  # open file for writing

def myfunc(y):
   if y >= 0.0:
       return y ** 5 * math.exp(-y)
   else:
       return 0.0

# Loop through y values, using slices to start at position 3
# and get every second value
for i, y in enumerate(sys.argv[3::2]):

    # The corresponding x value is the one before the selected y value
    x = sys.argv[2:][i*2]

    # Call myfunc with y, converting y from string to float.
    fy = myfunc(float(y))

    # Write output using f-strings
    ofile.write(f'({x}, {fy})\n')

相关问题 更多 >

    热门问题