使用C#BinaryReader读取python二进制文件
我需要使用python将一些数据(如整数、浮点等)导出到二进制文件中。之后,我不得不用C#再次读取该文件,但它对我不起作用 我尝试了几种用python编写二进制文件的方法,只要我也用python阅读它,它就会工作:使用C#BinaryReader读取python二进制文件,python,c#,binary,binaryfiles,Python,C#,Binary,Binaryfiles,我需要使用python将一些数据(如整数、浮点等)导出到二进制文件中。之后,我不得不用C#再次读取该文件,但它对我不起作用 我尝试了几种用python编写二进制文件的方法,只要我也用python阅读它,它就会工作: a = 3 b = 5 with open('test.tcd', 'wb') as file: file.write(bytes(a)) file.write(bytes(b)) 或者这样写: import pickle as p with open('tes
a = 3
b = 5
with open('test.tcd', 'wb') as file:
file.write(bytes(a))
file.write(bytes(b))
或者这样写:
import pickle as p
with open('test.tcd', 'wb') as file:
p.dump([a, b], file)
static void LoadFile(String path)
{
BinaryReader br = new BinaryReader(new FileStream(path, FileMode.Open));
int a = br.ReadInt32();
int b = br.ReadInt32();
System.Diagnostics.Debug.WriteLine(a);
System.Diagnostics.Debug.WriteLine(b);
br.Close();
}
目前我正在用C#读取文件,如下所示:
import pickle as p
with open('test.tcd', 'wb') as file:
p.dump([a, b], file)
static void LoadFile(String path)
{
BinaryReader br = new BinaryReader(new FileStream(path, FileMode.Open));
int a = br.ReadInt32();
int b = br.ReadInt32();
System.Diagnostics.Debug.WriteLine(a);
System.Diagnostics.Debug.WriteLine(b);
br.Close();
}
不幸的是,输出不是3和5,相反,我的输出只是零。如何正确读取或写入二进制文件?python可能没有以C所期望的格式写入数据。您可能需要交换字节结束或执行其他操作。您可以改为读取原始字节,并使用
位转换器
查看是否修复了它
另一种选择是在python中显式指定endian,我认为big-endian是C#的默认二进制读取器格式
an_int=5
a_bytes_big=a_int.to_bytes(2,‘big’)
打印(a_字节_大)
输出
b'\x00\x05'
a_bytes_little=a_int.to_bytes(2,‘little’)
打印(a_字节_小)
输出
b'\x05\x00'
在Python中,必须用4个字节编写整数。请在此处阅读更多信息:
a=3
b=5
以open('test.tcd','wb')作为文件:
f、 write(struct.pack)(“我会使用一些文件格式:csv、avro等,这两种语言都有库。如果在您的情况下不可能,那么您应该澄清这个问题。非常感谢!它工作得非常好,感谢添加struct.pack参考!:d