Python Forum
Noob question about import files
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Noob question about import files
#1
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
Reply
#2
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 = []).
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
Smile A basic question from a noob AncientMantra 3 3,286 Apr-09-2021, 02:20 AM
Last Post: MH90000

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020