Python Windows将十六进制到BIN写入fi

2024-04-25 19:34:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下脚本,它将二进制文件作为十六进制保存到变量中,并将其作为二进制文件转储到文件中,在Linux下一切正常,但在Windows下失败,我不知道为什么:

import os, os.path
from ctypes import *
import sys, binascii

current_dir = r".\\"
startup = "4d5a90000300000004000000ffff0000b800000000000000400000000000000000000000000000000000000000000000000000000000000000" # snipped, too big to have it here

def DumpStartupFile():
        startupbin=binascii.unhexlify(startup)
        o=open(current_dir+"\\startup.exe","w")
        o.write(startupbin)

if os.path.isfile(current_dir+"\\startup.exe"):
        True
else:
        DumpStartupFile()

你知道为什么在Windows下会失败吗?在


Tags: 文件pathimport脚本oslinuxwindowsdir
1条回答
网友
1楼 · 发布于 2024-04-25 19:34:25

在写入二进制数据时,您总是希望以二进制模式打开文件:

o=open(current_dir+"\\startup.exe","wb")
o.write(startupbin)

特别是在Windows上,在text modus中打开一个文件会导致换行在写入时被转换为平台本地值,但这对于二进制数据来说不是理想的行为。在

^{} function documentation

The default is to use text mode, which may convert '\n' characters to a platform-specific representation on writing and back on reading. Thus, when opening a binary file, you should append 'b' to the mode value to open the file in binary mode, which will improve portability. (Appending 'b' is useful even on systems that don’t treat binary and text files differently, where it serves as documentation.)

相关问题 更多 >