The file object has a readlines method that loads the file into a list of line strings all at once:
f = open('main.py') lines = f.readlines() print( lines )
To remove the empty space for each in in the file
f = open('main.py') lines = f.readlines() # w ww. j ava2 s.c o m lines = [line.rstrip() for line in lines] print( lines )
The code above can be rewritten as the follows.
lines = [line.rstrip() for line in open('main.py')] print( lines )
The following code shows more examples for List Comprehensions on Files
print( [line.upper() for line in open('main.py')] ) print( [line.rstrip().upper() for line in open('main.py')] ) print( [line.split() for line in open('main.py')] ) print( [line.replace(' ', '!') for line in open('main.py')] ) print( [('sys' in line, line[:5]) for line in open('main.py')] )