40

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?

Abdul Fatir
  • 6,159
  • 5
  • 31
  • 58
UcanDoIt
  • 1,775
  • 7
  • 20
  • 27

8 Answers8

97

It's a lot easier than that:

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

This returns a list of each line in the file.

David Hall
  • 32,624
  • 10
  • 90
  • 127
Brian C. Lane
  • 4,073
  • 1
  • 24
  • 23
67

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.

Absulit
  • 1,885
  • 1
  • 17
  • 17
11
my_list = [line.split(',') for line in open("filename.txt")]
orip
  • 73,323
  • 21
  • 116
  • 148
  • 2
    I fear jumping into a list comprehension for someone still trying to understand basic python might be a bit large of a step. :) – Dustin Nov 29 '08 at 22:08
  • Dustin is right, however orip offered the most correct answer to the question. – tzot Nov 30 '08 at 08:23
  • 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? – interstellar Mar 27 '16 at 15:52
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(','))
Dustin
  • 89,080
  • 21
  • 111
  • 133
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.

S.Lott
  • 384,516
  • 81
  • 508
  • 779
  • 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 – UcanDoIt Nov 29 '08 at 22:09
  • 1
    While you're on conventions, PEP8 also has something to say about spaces inside of parentheses. :) – Dustin Nov 29 '08 at 22:11
  • See http://www.python.org/dev/peps/pep-0008/, also see http://stackoverflow.com/questions/159720/what-is-the-naming-convention-in-python-for-variable-and-function-names – S.Lott Nov 29 '08 at 22:12
  • @Dustin: well aware of space-in-parenthesis recommendation in PEP8. After 3 decades of spaces in ()'s, I'm not going to change. – S.Lott Nov 29 '08 at 22:13
  • @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. :) – Dustin Nov 29 '08 at 23:03
  • @Dustin: Yes, trivial spacing inconsistencies are inconsistent. I've seen so much code that simply doesn't work in the first place. I feel that "working" trumps "consistent spacing". If spacing leads to difficulty understanding, then there are larger problems to solve first. – S.Lott Nov 30 '08 at 03:41
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 ]
hasen
  • 161,647
  • 65
  • 194
  • 231
1

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())
Jonathan Koren
  • 883
  • 7
  • 9
0

... 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() 
Andre Nevares
  • 711
  • 6
  • 21