Python - Using List Comprehensions on Files

Introduction

The file object has a readlines method that loads the file into a list of line strings all at once:

Demo

f = open('main.py') 
lines = f.readlines() 
print( lines )

Result

To remove the empty space for each in in the file

Demo

f = open('main.py') 
lines = f.readlines() # from w  w w  . j ava2 s . c  o m
lines = [line.rstrip() for line in lines] 
print( lines )

Result

The code above can be rewritten as the follows.

Demo

lines = [line.rstrip() for line in open('main.py')] 
print( lines )

Result

The following code shows more examples for List Comprehensions on Files

Demo

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')] )

Result

Related Example