Cam
Cam

Reputation: 2210

Reading lines from a file in Jython

Ok, I know this is going to sound like a homework question (because it kind of is), but our lecturer has thrown us in the deep end with this and I need a little help, my google-fu is failing. As part of an assignment I need to read in data from a text file, and copy each line of the text file into an array/list. What I've done is not working. What I have so far:

def main():
  file = open(pickAFile())

  lines = []
  index = 0

  for line in file:
    lines[index] = line
    index = index + 1

But this comes back with: The error value is: list assignment index out of range Sequence index out of range. The index you're using goes beyond the size of that data (too low or high). For instance, maybe you tried to access OurArray[10] and OurArray only has 5 elements in it.

Any help would be most welcome!

Upvotes: 0

Views: 3948

Answers (3)

Praveen
Praveen

Reputation: 9365

To read file into list you can try:

with open("file.txt") as f:
    lines = f.readlines()

or

lines = [line for line in open("file.txt")]

Here each line will have \n characters. To remove that use, line.rtrim('\n')

Upvotes: 0

DeepSpace
DeepSpace

Reputation: 81684

The problem is in the line lines[index] = line. There is nothing in lines[0] in the first iteration.

You need to change this line to lines.append(line), and you don't need to keep track after index, so your whole code should look like:

def main():
    file = open(pickAFile())

    lines = []

    for line in file:
        lines.append(line)

append adds the parameter that it receives to the last index in the list that it is called with, see the docs.

Upvotes: 1

Holt
Holt

Reputation: 37706

You cannot extend list like this, if your list is empty (lines = []), then lines[index] is trying to access a non existing index and thus throws an error.

If you want to append something to your list, use the append function:

lines.append(line)

But if you want to read all the lines in a file, you'd better use the readlines method:

lines = file.readlines()

Upvotes: 0

Related Questions