我编写了一个简单的python模块,它读取文件并将读取的数据转换为十六进制值列表。然后我将每个值递增1.我想知道如何将这个十六进制值列表写入新文件。
使用python 3.x
代码:
inFilePath = input("Input File: ")
inFile = open(inFilePath, "rb")
data = inFile.read()
hexVals = []
for byte in data:
hexVals.append(hex(byte))
print("File Read")
print("Original Data: " + str(hexVals))
for x in range(hexVals.__len__()):
hexVals[x] = hex(int(hexVals[x], 16) + 1)
print("Altered Data: " + str(hexVals))
outFilePath = input("Output File: ")
outFile = open(outFilePath, "wb")
outFile.write(???)
答案 0 :(得分:0)
您将字节存储为十六进制字符串。你可以这样做,但它已经把结果作为整数给你了。只需将其保留为整数,但您可能希望将其转换为列表。在将其转换为列表后,您可以以相当简单的方式将其转换回bytes
。例如:
with open('input', 'rb') as f:
data = f.read()
data = list(data)
data = [byte + 1 for byte in data]
data = bytes(data)
# If this is all you're going to do, you could just do this:
# data = bytes((byte + 1) % 256 for byte in data)
with open('output', 'wb') as f:
f.write(data)
答案 1 :(得分:0)
你快到了!这样可行。
outFile.write('\n'.join(hexVals))
outFile.close()
不要忘记关闭输入文件,或使用icktoofay建议的with
语法。