My code
with open('car.FT','r', encoding="utf-8",errors='ignore') as h:
for line in h:
print(line)
File "car.FT" is output of Fourier transform that has complex values stored.It is written through a C program but I want to open this file in python. The output is not readable with this above piece of code used. The file is written in C :
typedef struct complex { /* Define a complex type */
float r,i; /* Real and imaginery parts */
} COMPLEX;
/* buffer for input image being converted into complex type */
COMPLEX IN_BUF[ROWS][COLS];
///PROCESSING ON IN_BUF////
fwrite(IN_BUF, sizeof(COMPLEX), ROWS*COLS, fout);
Here below is the data actually in the file. That I want to read.
I want to read this above file data in python.
Judging by the C code the numbers are written as binary float numbers, and what you are showing is the hex output of the file contents. In this case, you have to read the binary contents, while you are trying to read it as a text file.
You have to open the file in binary mode (rb
), read and convert each float value (which is 4 bytes long) using struct.unpack
, and convert pairs of float to complex
. Here is a simple implementation (untested):
from struct import unpack
numbers = []
with open(filename, "rb") as f:
data = f.read() # read all data
count = len(data) // 8 # each complex number takes 8 bytes
i = 0
for index in range(count):
# "f" means float (4 bytes); unpack returns a tuple with one value
real = unpack("f", data[i:i + 4])[0]
i += 4
im = unpack("f", data[i:i + 4])[0]
i += 4
numbers.append(complex(real, im))
print(numbers)