Python Forum

Full Version: Noob question about import files
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi,

I've got a file consisting of dates, GD17, electric and heat. The teacher wants me to make a list and also that the date
has a string and everything else as a float.
When I try this, I get:

def load_data( filename, skiprows):
infile = open('load_data.csv','r')
infile.readline()
load_data()

for lines in infile:
date = str(infile[line[0]])
GD17 = float(infile[lines[1]])
Electric = float(infile[lines[2]])
Heat = float(infile[lines[3]])
load_data.append([date, GD17, Electric, Heat])

TypeError: '_io.TextIOWrapper' object is not subscriptable
I'm assuming the complete lack of indentation is a copy-and-paste error. Try to get the proper indentation so we can see the code you are actually running.

The simple way of reading through a file is:

infile  = open('load_data.csv') # 'r' is the default, you don't need it
infile.readline()               # this reads one line, if your file has a header line
for line in infile:             # this loops through the file, ONE line each time through the loop
    do_something_with_line()    # dummy code
You are going to want to look into the split method of strings to break up the line into the fields you want. That will result in a list, which is what you would using the indexing on.

If you want to make a list of rows that you can append to, as in line 11, you want to initialize them as an empty list (data = []).