将 Mac 的 python 代码转换为 Windows
我是 python 新手,我对一段 python 代码有疑问,该代码从模型输出文件创建清理后的输出文件。这段代码是为 Mac 用户编写的,但现在我想在 Windows 中运行它。但它给出了错误消息。您能帮我转换此代码以便我可以在 Windows 中使用它吗?谢谢。
import sys
if len(sys.argv) > 1:
fileName = sys.argv[1]
else:
print "selected_um_b.out" #insert file name here
sys.exit()
f = open(fileName)
counter = 0
fw = open(fileName+".cleaned", 'w')
for line in f:
line = line.strip()
counter = counter + 1
if counter <= 4:
fw.write(line+"\n");
continue
values = line.split("\t")
if (values[4].strip() == "-99" or values[5].strip() == "0"): continue
fw.write("\t".join(values)+"\n")
f.close()
更新
错误消息是:
回溯(最近一次调用最后一次):文件 “C:\Trial_batch\clean_output.py”,第 7 行,在 sys.exit() 中 系统退出
I am new to python and I have a question about a piece of python code that creates a cleaned up output file from a model output file. This code was written for a Mac user, but now I want to run it in Windows. But it gives an error message. Could you help me in converting this code so I can use it in Windows? Thanks.
import sys
if len(sys.argv) > 1:
fileName = sys.argv[1]
else:
print "selected_um_b.out" #insert file name here
sys.exit()
f = open(fileName)
counter = 0
fw = open(fileName+".cleaned", 'w')
for line in f:
line = line.strip()
counter = counter + 1
if counter <= 4:
fw.write(line+"\n");
continue
values = line.split("\t")
if (values[4].strip() == "-99" or values[5].strip() == "0"): continue
fw.write("\t".join(values)+"\n")
f.close()
Update
The error message is:
Traceback (most recent call last): File
"C:\trial_batch\clean_output.py", line 7, in sys.exit()
SystemExit
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当您执行该程序时,它需要命令行上的文件名。看来您没有提供,因此程序退出(
sys.exit()
调用终止程序)。你想如何使用它?如果您只想转换一个文件,请将文件和Python脚本放在同一目录中。将第 3 行到第 7 行替换为
filename = "yourfilename.typ"
(不要缩进该行);它将读取文件(在我的示例中为“yourfilename.typ”)并写入文件名中带有“cleaned”的输出文件。The program expects a filename on the command line when you execute it. It appears you did not provide one, so the program exited (the
sys.exit()
call terminates the program).How are you trying to use it? If you just want to convert one file, put the file and the Python script into the same directory. Replace lines 3 through 7 with
filename = "yourfilename.typ"
(do not indent the line); it will read the file ("yourfilename.typ" in my example) and write an output file with 'cleaned' in the filename.