Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a List that contain each Line of a File

Tags:

python

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?

like image 638
UcanDoIt Avatar asked Nov 29 '08 21:11

UcanDoIt


People also ask

Which method returns a list containing each line of the file as a list item?

The readlines() method returns a list containing each line in the file as a list item.


1 Answers

It's a lot easier than that:

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

This returns a list of each line in the file.

like image 82
Brian C. Lane Avatar answered Oct 10 '22 11:10

Brian C. Lane