我正在尝试编写一系列我从头开始构建的测试文件。数据有效负载生成器的输出是字符串类型,我正在努力将字符串直接写入文件。
有效负载构建器仅使用十六进制值,并且只需为每次迭代添加一个字节。
我尝试过的“写入”函数要么都落在字符串的写入上,要么为字符串写入 ASCII 代码,而不是字符串本身......
我想最终得到一系列文件 - 具有与数据有效负载相同的文件名(例如文件 ff.txt 包含字节 0xff
def doMakeData(counter):
dataPayload = "%X" %counter
if len(dataPayload)%2==1:
dataPayload = str('0') + str(dataPayload)
fileName = path+str(dataPayload)+".txt"
return dataPayload, fileName
def doFilenameMaker(counter):
counter += 1
return counter
def saveFile(dataPayload, fileName):
# with open(fileName, "w") as text_file:
# text_file.write("%s"%dataPayload) #this just writes the ASCII for the string
f = file(fileName, 'wb')
dataPayload.write(f) #this also writes the ASCII for the string
f.close()
return
if __name__ == "__main__":
path = "C:\Users\me\Desktop\output\\"
counter = 0
iterator = 100
while counter < iterator:
counter = doFilenameMaker(counter)
dataPayload, fileName = doMakeData(counter)
print type(dataPayload)
saveFile(dataPayload, fileName)
要只写入一个字节,请使用chr(n)
获取包含整数的字节n
.
您的代码可以简化为:
import os
path = r'C:\Users\me\Desktop\output'
for counter in xrange(100):
with open(os.path.join(path,'{:02x}.txt'.format(counter)),'wb') as f:
f.write(chr(counter))
请注意路径使用原始字符串。如果字符串中有“\r”或“\n”,它们将被视为回车或换行,而不使用原始字符串。
f.write
是写入文件的方法。chr(counter)
生成字节。确保以二进制模式写入'wb'
以及。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)