0

I am trying to create a function get_data which takes in a file name and column number, and returns the numbers (as floats) found in the column.

This is my code.

def get_data(filename, columnnumber):
    open(filename, 'r').readlines()
    columnnumber = []
    return columnnumber

 
wind = get_data('blizzard.txt',0)
print(wind)

The output should be like

wind = get_data('blizzard.txt',0)
print(wind)
 
28
29.2
15.1
30.1
32.1
31.3
32.5
33.1
34.1
33.3
32.1
33.8
29.1
30.9
31.5
25.5
26
27
25.1
33.1
33.4
32.1
29.4
30

But all i get is either one row of value or nothing.

1 Answers1

1

If it is just a basic .txt file where the values are separated by some delimiter with no headers or anything then all you need to do is

def get_data(filename, columnnumber, delimiter=','):
    with open(filename, 'r') as file:
        data = file.readlines()
    retrieved_data = [x.strip().split(delimiter)[columnnumber] for x in data]
    return retrieved_data

Modify the delimiter as needed based on how the data is defined in your .txt file. ex: this code would work for rows defined like 13,34

line 2 and 3: the with open line is used to ensure that your file always closes cleanly. It's good practice to open files this way.
line 4: consider the line '13,34\n' read from the file stored in x. x.strip() removes the new line character \n so we're left with '13,34' and the split function splits as the ',' character so it yields list_temp = ['13', '34']. Then you use list indexing to pull out the value so list_temp[0] or list_temp[1]. the for x in data part just applies the above explanation to every line read into the data list variable

For ease of understanding the below code would yield the same results:

def get_data(filename, columnnumber, delimiter=','):
    with open(filename, 'r') as file:
        data = file.readlines()
    retrieved_data = []
    for line in data:
        line = line.strip()
        row_vals = line.split(delimiter)
        col_val = row_vals[columnnumber]
        retrieved_data.append(col_val)
    return retrieved_data
Sharpfawkes
  • 549
  • 1
  • 8
  • 15
  • can you explain line 2 to line 5? Why must the with function be used? what does [x.split(delimiter)[columnnumber] for x in data] this mean? – Seah Jia Hui Mar 08 '21 at 18:20