写一个“字符串"作为原始二进制文件放入文件 Python

Write a quot;stringquot; as raw binary into a file Python(写一个“字符串作为原始二进制文件放入文件 Python)

本文介绍了写一个“字符串"作为原始二进制文件放入文件 Python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一系列用于测试的文件,这些文件是我从头开始构建的.数据有效负载构建器的输出是字符串类型,我正在努力将字符串直接写入文件.

I'm trying to write a series of files for testing that I am building from scratch. The output of the data payload builder is of type string, and I'm struggling to get the string written directly to the file.

有效负载构建器仅使用十六进制值,并且只是为每次迭代添加一个字节.

The payload builder only uses hex values, and simply adds a byte for each iteration.

我尝试过的所有'write'函数都不是写字符串,就是写字符串的ASCII码,而不是字符串本身......

The 'write' functions I have tried all either fall over the writing of strings, or write the ASCII code for the string, rather than the string its self...

我想以一系列文件结束 - 与数据负载具有相同的文件名(例如,文件 ff.txt 包含字节 0xff

I want to end up with a series of files - with the same filename as the data payload (e.g. file ff.txt contains the byte 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:UsersmeDesktopoutput\"
    counter = 0
    iterator = 100
    while counter < iterator:
        counter = doFilenameMaker(counter)
        dataPayload, fileName = doMakeData(counter)
        print type(dataPayload)
        saveFile(dataPayload, fileName)

推荐答案

要只写入一个字节,请使用 chr(n) 获取包含整数 n 的字节.

To write just a byte, use chr(n) to get a byte containing integer n.

您的代码可以简化为:

import os
path = r'C:UsersmeDesktopoutput'
for counter in xrange(100):
    with open(os.path.join(path,'{:02x}.txt'.format(counter)),'wb') as f:
        f.write(chr(counter))

注意路径使用原始字符串.如果字符串中有 ' ' 或 ' ' ,它们将被视为回车或换行,而不使用原始字符串.

Note use of raw string for the path. If you had a ' ' or ' ' in the string they would be treated as a carriage return or linefeed without using a raw string.

f.write 是写入文件的方法.chr(counter) 生成字节.确保也以二进制模式写入 'wb'.

f.write is the method to write to a file. chr(counter) generates the byte. Make sure to write in binary mode 'wb' as well.

这篇关于写一个“字符串"作为原始二进制文件放入文件 Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:写一个“字符串"作为原始二进制文件放入文件 Python

基础教程推荐