在阅读学习Python困难之路几周后,我想尝试创建一个小程序来读取[文本文件包含hex]并写入另一个文件[as decimal]。我希望在输入命令行python convert_hex.py hex.txt
后,Python会创建一个名为hex_1.txt
的新文件。
#this is content from hex.txt
0x5B03FA01
0x42018360
0x9FF943B3
这就是我期望我的python提供输出
#this is content from hex_1.txt
1526987265
1107395424
2683913139
经过3小时的反复试验。我可以按照我想要的方式看到结果。代码如下;
from sys import argv
from os.path import exists
def hex2dec (hex):
result_dec = int(hex, 0)
return result_dec
script, from_file = argv
to_file = from_file[:len(from_file)-4] + "_1.txt"
out_file = open(to_file, 'w').close()
with open(from_file) as in_file:
lines = in_file.read().splitlines()
for i in lines:
converted = str(hex2dec (i))
out_file = open(to_file, 'a+')
out_file.write(converted + "\n")
out_file.close()
print "converted =" + str(converted)
print "done."
但我认为我应该进一步研究很多领域,例如: hex2dec函数中的bug处理。有人可以建议我进一步研究改进这段代码吗?