387,693 views
0 votes
0 votes
write a program that reads the contents of this file, assigns the header lines to a variable that is a list of strings, and assigns the data to a variable that is a floating point np.array that contains all of the data in the file. (the data should be in a 4 x 3 array.) write this code using standard file i/o commands; do not use any csv reader that you may know of in some python package.

User Sguha
by
2.9k points

1 Answer

15 votes
15 votes

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)

User Gavin Campbell
by
3.3k points