1

Can a binary file created by a .NET program be read by Python and vice versa?

Which data types would be compatible for this?

Example VB.NET program:

Sub Main()
    Using writer As New System.IO.BinaryWriter( _
    System.IO.File.Open("Test.bin", IO.FileMode.Create))
        writer.Write(True)
        writer.Write(123)
        writer.Write(123.456)
        writer.Write(987.654D)
        writer.Write("Test string.")
    End Using
    Using reader As New System.IO.BinaryReader( _
    System.IO.File.Open("Test.bin", IO.FileMode.Open))
        Console.WriteLine(reader.ReadBoolean())
        Console.WriteLine(reader.ReadInt32())
        Console.WriteLine(reader.ReadDouble())
        Console.WriteLine(reader.ReadDecimal())
        Console.WriteLine(reader.ReadString())
    End Using
    Console.Write("Press <RETURN> to exit.")
    Console.ReadKey()
End Sub
mcu
  • 3,302
  • 8
  • 38
  • 64

1 Answers1

1

It's very unlikely that Python uses identical conventions for storing binary data.

Issues to be aware of include everything from endianess to how data structures are laid out. Intel CPUs use least-significant bit ordering, the TCP/IP network protocol and many non-Intel CPUs including the CPUs that UNIX traditionally ran on, use most-significant bit ordering. A platform-agnostic system like .NET will stick with one ordering when it writes binary files. So .NET will be compatible with itself whether it's running on a Core i7 or ARM or some other CPU. But even if Python consistently uses the same ordering as .NET, it's just completely unlikely that it is going to lay out data types and data structures the same way.

This leaves you in the position if needing to use a compatible file IO library on both platforms, which is more work than you want to sign up for.

Fortunately, there are libraries available for your use. See this answer for one example.

Of course, the modern friendly way to do this sort of thing is to write out a delimited text file in a format like XML or JSON. Or, if you're dealing with very large data sets, just use a database.

Community
  • 1
  • 1
Craig Tullis
  • 9,939
  • 2
  • 21
  • 21