views:

264

answers:

5

How do I read every line of a file in Python and store each line as an element in an array?

I want to read the file line by line and each line is appended to the end of the array. I could not find how to do this anywhere and I couldn't find how to create an array of strings in Python.

+3  A: 

This will yield an "array" of lines from the file.

lines = tuple(open(filename, 'r'))
Noctis Skytower
+1  A: 

This is more explicit than necessary, but does what you want.

ins = open( "file.txt", "r" )
array = []
for line in ins:
    array.append( line )
robert
thanks it worked
Julie Raswick
You want to be sure to call ins.close() if you use this method
aaronasterling
+4  A: 

See Input and Ouput:

f = open('filename')
lines = f.readlines()
f.close()

or with stripping the newline character:

lines = [line.strip() for line in open('filename')]
Felix Kling
+6  A: 
with open(fname) as f:
    content = f.readlines()

I guess you're meant list and not array.

SilentGhost
+2  A: 

You use readlines to read all of the lines of the file in at once:

f = open('somefile.txt','r') 
for line in f.readlines(): 
  print line 
f.close()

Or you can read them in one at a time:

 f = open('somefile.txt','r') 
 for line in f.read().split('\n'): 
    print line 
 f.close()
Justin Ethier
that's not how to read "one at a time".
SilentGhost
@Justin You can iterate directly over a file handle: `for line in f: print line`.
FM