Answer:
import numpy as np
f = open("data.dat", "r")
header = [] # to store the header lines
numbers = [] # to store numbers
for line in f.readlines():
if(line[0]=="#"):
header.append(line[2:-1])
else:
for num in line.split(", "):
numbers.append(num)
# convert number strings to float
for i in range(len(numbers)):
if(numbers[i][-1]=="\\"):
numbers[i] = float(numbers[i][:-1])
else:
numbers[i] = float(numbers[i])
# convertin list to numpy array
ans = np.array(numbers)
ans = ans.reshape(4,3)
print(header)
print(ans)
print(ans.dtype)
or
import numpy as np
def read_file(filename):
"""Reads a file and returns the header and data as a list and a numpy array, respectively."""
with open(filename, 'r') as f:
header = []
data = []
for line in f:
if line.startswith('#'):
header.append(line)
else:
data.append(line)
data = np.array([line.split() for line in data], dtype=float)
return header, data
if __name__ == '__main__':
header, data = read_file('data.dat') # read the file
print(header)
print(data)