Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 文件中不需要的十六进制值_Python_Python 3.x_Linux_Hex - Fatal编程技术网

Python 文件中不需要的十六进制值

Python 文件中不需要的十六进制值,python,python-3.x,linux,hex,Python,Python 3.x,Linux,Hex,我创建了一个小python3脚本,如下所示: 导入系统 将open(sys.argv[1],'r')作为f: hex_data=f.readline().split() 将open('hexConverted','a')作为e: 对于十六进制数据中的i: 打印(“将{}写入文件”.format(i))#用于调试 e、 写入(chr(int(i,16))) 它以以下格式读取文件'f': 89 50 4e 47 0d 0a 1a 0a 00 00 00 0d 49 48 44 52 并创建一个新

我创建了一个小python3脚本,如下所示:

导入系统 将open(sys.argv[1],'r')作为f: hex_data=f.readline().split() 将open('hexConverted','a')作为e: 对于十六进制数据中的i: 打印(“将{}写入文件”.format(i))#用于调试 e、 写入(chr(int(i,16))) 它以以下格式读取文件'f'

89 50 4e 47 0d 0a 1a 0a 00 00 00 0d 49 48 44 52
并创建一个新文件,其中十六进制值与上面提供的十六进制值相同。但每次开始时它都会附加一个不需要的\xC2

$hextump-C hextconverted
00000000 c2 89 50 4e 47 0d 0a 1a 0a 00 00 D 49 48 44 |…巴布亚新几内亚……IHD|
0000001052 | R|
00000011

即使调试print命令也没有提到这个十六进制值。为什么会这样

为了澄清我的评论,您需要在open中添加“b”,然后将bytes对象传递给write。如果不这样做,它将尝试将文件编码为unicode,c2是一种特殊的unicode代码

import sys

with open(sys.argv[1], 'r') as f:
    hex_data = f.readline().split()
    with open('hexConverted', 'ab') as e:
        for i in hex_data:
            print("Writing {} in file".format(i))
            e.write(int(i,16).to_bytes(1,'big'))

为了澄清我的评论,您需要在open中添加“b”,然后将bytes对象传递给write。如果不这样做,它将尝试将文件编码为unicode,c2是一种特殊的unicode代码

import sys

with open(sys.argv[1], 'r') as f:
    hex_data = f.readline().split()
    with open('hexConverted', 'ab') as e:
        for i in hex_data:
            print("Writing {} in file".format(i))
            e.write(int(i,16).to_bytes(1,'big'))
您是否尝试将“b”添加到open以指定二进制格式<代码>打开('hexConverted','ab')您是否尝试将“b”添加到打开中以指定二进制格式<代码>打开('hexConverted','ab')