我是python的新手,我正在尝试编写一个简单的脚本,将包含小数的.txt文件的每一行转换为十六进制格式,并将其保存到另一个.txt文件中。我的输入具有十进制格式的16位值,例如
15166
46818
26814
640
44756
27831
2646
这是我到目前为止的一个片段:
import binascii
filename = '1.txt'
content = f.read()
out = binascii.hexlify(content)
f = open('out.txt', 'wb')
f.write(out)
f.close()
这是我正在31353136360d0a34363831380d0a32363831340d0a3634300d0a34343735360d0a32373833310d0a323634360d0a393237360d0a323238390d0a333330320d0a33393137370d0a393535340d0a363239310d0a31353438310d0a33353632300d0a35373330310d0a33323933350d0a3834380d0a34313639330d0a33353538340d0a31363936390d0a31313539300d0a31343639350d0a36333931350d0a393238340d0a33323339370d0a343235330d0a33323934320d0a31303139340d0a34393238360d0a34383430370d0a31333330350d0a3336340d0a36323735340d0a32313438310d0a35323734350d0a31303931310d0a34323835380d0a373731370d0a34393530320d0a35313034380d0a36323832330d0a34343833370d0a36313934300d0a33393137310d0a33333032320d0a32333836360d0a36313335360d0a31393038380d0a35393135340d0a36353335320d0a32343233300d0a32303936310d0a34313134330d0a35343433350d0a36343038380d0a35323334340d0a33373136370d0a32363734390d0a36353439300d0a36353236360d0a36313234320d0a33343933360d0a313532360d0a35313236310d0a33353039350d0a36303931350d0a34313336350d0a32333235370d0a333133350d0a33373433380d0a输出34363837350d0a363831390d0a34373034320d0a31373035380d0a363734350d0a35313135340d0a333535330d0a33343134320d0a36353334360d0a34343334310d0a35333330370d0a35333232320d0a34313336300d0a33383037300d0a32363134350d0a34343532310d0a34373836360d0a34393033360d0a36323037320d0a34373630330d0a34363337300d0a34303534360d0a31393231330d0a373930340d0a393839340d0a31383337350d0a35383231360d0a33353033380d0a31333338310d0a32313637350d0a33383333370d0a35393430340d0a31333933300d0a31353830370d0a33373434370d0a31313832370d0a34383331360d0a32393433350d0a32363831360d0a36313035360d0a34303533350d0a33383335340d0a31373037370d0a34383236360d0a31363237350d0a34343331370d0a35343836320d0a34303730370d0a32363735370d0a32353438380d0a3737320d0a32363038330d0a32373339370d0a35323934380d0a34313537340d0a32363934310d0a3433353539
所以我需要将每个条目分开并在输出文件中显示为列表。如果我有线
for c in out:
print(c)
我得到了每个中包含两位小数的巨大列表,似乎是错误的。请为此问题发布任何解决方案。
答案 0 :(得分:0)
另一种方法是使用hex
,如下所示:
filename = '1.txt'
newfile = '2.txt'
with open(filename, 'r') as f:
numbers = f.read().splitlines()
with open(newfile, 'w') as n:
for num in numbers:
n.write('{}\n'.format(hex(int(num))))