我是一个完全的编程新手 - 三周前才开始学习,目前只学了codecademy的Python课程 - 所以需要简单易懂的解释!
我正在尝试编写一个Python脚本,将文件作为HEX字符串读取,然后根据在HEX字符串中找到的“magic number”将文件解析成单独的输出文件。
例如:如果我的HEX字符串是“0011AABB00BBAACC00223344”,我可能想要根据魔术数字“00”将此字符串解析为新的输出文件,并告诉Python每个输出应为8个字符长。 上面示例字符串的输出应该是包含HEX值的3个文件:
"0011AABB" "00BBAACC" "00223344"
这是我目前的代码(假设在此情况下上述字符串包含在“hextests”文件中):
import os
import binascii
filename = "hextests"
# read file as a binary string
with open(filename, 'rb') as f:
content = f.read()
# convert binary string to hex string
hexString = binascii.hexlify(content)
# define magic number as "00"
magic_N = "00"
# attempting to create a new substring called newFile that is equal to each instance magic_N repeats throughout the file for a length of 8 characters
for chars in hexString:
newFile = ""
if chars == magic_N:
newFile += chars.len(9)
# attempting to create a series of new output files for each instance of newFile - while incrementing the output file name
if newFile != "":
i = 0
while os.path.exists("output_file%s.xyz" % i):
i += 1
fh = with open("output_file%s.xyz" % i, "wb"):
newFile
我相信这里有很多错误需要解决,而且可能比我想象的更加复杂...但我的主要问题与定义
chars
和newFile
变量的正确方式有关。我非常确定python只会将chars
视为字符串中的单个字符,因此它会失败,因为我试图搜索比一个字符长的magic_N
。我是否正确地认为这是问题的一部分?另外,如果您了解此脚本的主要目标,请问是否还有其他建议我应该做出改变?
非常感谢您的帮助!