1

I really like how .NET implements reading/writing of binary data to a file. Clean and elegant.

Can I do this in Python?

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
3
  • Yes. Use ´with´ with open, see the example: docs.python.org/3/library/functions.html#open with open("file.txt") as file: Commented Oct 18, 2015 at 19:09
  • Yes, I understand context managers, but how can I write a bool, int, float, str, decimal.Decimal, etc. I have seen solutions that write whole structures, like lists or classes, for example using the pickle module, but not so much individual values. That is why I used 'Random' in the question title. Commented Oct 18, 2015 at 19:14
  • 1
    Ahh, I see. But I don't think something like that exists in python. Use pickle... Commented Oct 18, 2015 at 19:20

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.