pythonc++file-writingfile-read

How to read a file in Python written out by C++


I have one program written in C++ that outputs the data from several different types of arrays. For simplicity, I'm using ints and just writing them out one at a time to figure this out.

I need to be able to read the file in on Python, but clearly am missing something. I'm having trouble translating the concepts from C++ over to Python.

This is the C++ I have that's working - it writes out two numbers to a file and then reads that file back in (yes, I have to use the ostream.write() and istream.read() functions - that's how at the base level the library I'm using does it and I can't change it).

int main(int argc, char **argv) {
  std::ofstream fout;
  std::ifstream fin;

  int outval1 = 1234;
  int outval2 = 5678;

  fout.open("out.txt");
  fout.write(reinterpret_cast<const char*>(&outval1), sizeof(int));
  fout.write(reinterpret_cast<const char*>(&outval2), sizeof(int));
  fout.close();
  
  int inval;
  fin.open("out.txt");

  while (fin.read(reinterpret_cast<char*>(&inval), sizeof(int))) {
    std::cout << inval << std::endl;
  }

  fin.close();

  return 0;
}

This is what I have on the Python side, but I know it's not correct. I don't think I should need to read in as binary but that's the only way it's working so far

with open("out.txt", "rb") as f:
    while (byte := f.read(1)):
        print(byte)

Solution

  • In the simple case you have provided, it is easy to write the Python code to read out 1234 and 5678 (assuming sizeof(int) is 4 bytes) by using int.from_bytes. And you should open the file in binary mode.

    import sys
    
    with open("out.txt", "rb") as f:
        while (byte := f.read(4)):
            print(int.from_bytes(byte, sys.byteorder))
    

    To deal with floats, you may want to try struct.unpack:

    import struct
    
    
    byte = f.read(4)
    print(struct.unpack("f", byte)[0])