42

I'm trying to open a file and create a list with each line read from the file.

   i=0
   List=[""]
   for Line in inFile:
      List[i]=Line.split(",")
      i+=1
   print List

But this sample code gives me an error because of the i+=1 saying that index is out of range. What's my problem here? How can I write the code in order to increment my list with every new Line in the InFile?

0

8 Answers 8

100

It's a lot easier than that:

List = open("filename.txt").readlines()

This returns a list of each line in the file.

Sign up to request clarification or add additional context in comments.

6 Comments

WoooW Just perfect! It worked. Btw imagine that was not a file... But i wnat to creat a dynamic list... How can I append an element on it? like if was an arrayList? ty so much
The append method will do the trick. For example: xs.append(line)
what about closing the file ?
No need to close it, python handles that automatically when the file goes out of scope.
Is there any way to strip the "/n" from the list generated ?
|
70

I did it this way

lines_list = open('file.txt').read().splitlines()

Every line comes with its end of line characters (\n\r); this way the characters are removed.

1 Comment

Thanks, this removes the newlines as I had expected from the accepted answer :) +1 for you
11
my_list = [line.split(',') for line in open("filename.txt")]

3 Comments

I fear jumping into a list comprehension for someone still trying to understand basic python might be a bit large of a step. :)
Dustin is right, however orip offered the most correct answer to the question.
I really like this method. However, at the end of each list, a \n is printed next to the last value on the line. How can I remove it?
10

Please read PEP8. You're swaying pretty far from python conventions.

If you want a list of lists of each line split by comma, I'd do this:

l = []
for line in in_file:
    l.append(line.split(','))

You'll get a newline on each record. If you don't want that:

l = []
for line in in_file:
    l.append(line.rstrip().split(','))

Comments

2

Assuming you also want to strip whitespace at beginning and end of each line, you can map the string strip function to the list returned by readlines:

map(str.strip, open('filename').readlines())

Comments

1

A file is almost a list of lines. You can trivially use it in a for loop.

myFile= open( "SomeFile.txt", "r" )
for x in myFile:
    print x
myFile.close()

Or, if you want an actual list of lines, simply create a list from the file.

myFile= open( "SomeFile.txt", "r" )
myLines = list( myFile )
myFile.close()
print len(myLines), myLines

You can't do someList[i] to put a new item at the end of a list. You must do someList.append(i).

Also, never start a simple variable name with an uppercase letter. List confuses folks who know Python.

Also, never use a built-in name as a variable. list is an existing data type, and using it as a variable confuses folks who know Python.

6 Comments

How can I leanr about python coding standards? Thanks, i didn't know you use varaibable names in lowercase... any special reason for that? Ty
While you're on conventions, PEP8 also has something to say about spaces inside of parentheses. :)
@Dustin: well aware of space-in-parenthesis recommendation in PEP8. After 3 decades of spaces in ()'s, I'm not going to change.
@Federico People who read your code and stop to think about why some parts look different from the rest of the code. :) e.g. what's special about the len() call that makes it consistent with PEP8, but inconsistent with the lines above it? If you don't care, just follow the conventions. :)
|
1

f.readlines() returns a list that contains each line as an item in the list

if you want eachline to be split(",") you can use list comprehensions

[ list.split(",") for line in file ]

Comments

1

... Also If you want to get rid of \n

In case the items on your list are with \n and you want to get rid of them:

with open('your_file.txt') as f:
    list= f.read().splitlines() 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.