问题是:
从命令行读取(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:
提示:在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文件的任何线索都将非常有用
这应该可以解决问题:
相关问题 更多 >
编程相关推荐