这是我的代码:
def decode(filename):
with open(filename, "rb") as binary_file:
# Read the whole file at once
data = bytearray( binary_file.read())
for i in range(len(data)):
data[i] = 0xff - data[i]
with open("out.log", "wb") as out:
out.write(data)
我有一个大约 10MB 的文件,我需要通过翻转每一位来翻译这个文件,并将其保存到一个新文件中。
使用我的代码翻译一个 10MB 的文件大约需要 1 秒,而使用 C 只需要不到 1 毫秒。
这是我的第一个 python 脚本。如果使用字节数组是正确的,我不知道。最耗时的代码是字节数组的循环。