python – How to read a file without newlines?

The Question :

431 people think this question is useful

In Python, calling

temp = open(filename,'r').readlines()

results in a list in which each element is a line in the file. It’s a little stupid but still: readlines() also writes newline character to each element, something I do not wish to happen.

How can I avoid it?

The Question Comments :
  • Use strip: [l.strip('\n\r') for l in temp]. Or even rstrip. And since iteration here it can be in open instead of in temp.
  • I would be nice if in Python 3 there was a value to set open’s newline argument to that chomped trailing newlines.
  • Related:…

The Answer 1

636 people think this answer is useful

You can read the whole file and split lines using str.splitlines:

temp =

Or you can strip the newline by hand:

temp = [line[:-1] for line in file]

Note: this last solution only works if the file ends with a newline, otherwise the last line will lose a character.

This assumption is true in most cases (especially for files created by text editors, which often do add an ending newline anyway).

If you want to avoid this you can add a newline at the end of file:

with open(the_file, 'r+') as f:, 2)  # go at the end of the file
    if != '\n':
        # add missing newline if not already present
    lines = [line[:-1] for line in f]

Or a simpler alternative is to strip the newline instead:

[line.rstrip('\n') for line in file]

Or even, although pretty unreadable:

[line[:-(line[-1] == '\n') or len(line)+1] for line in file]

Which exploits the fact that the return value of or isn’t a boolean, but the object that was evaluated true or false.

The readlines method is actually equivalent to:

def readlines(self):
    lines = []
    for line in iter(self.readline, ''):
    return lines

# or equivalently

def readlines(self):
    lines = []
    while True:
        line = self.readline()
        if not line:
    return lines

Since readline() keeps the newline also readlines() keeps it.

Note: for symmetry to readlines() the writelines() method does not add ending newlines, so f2.writelines(f.readlines()) produces an exact copy of f in f2.

The Answer 2

50 people think this answer is useful
temp = open(filename,'r').read().split('\n')

The Answer 3

18 people think this answer is useful

another example:

Reading file one row at the time. Removing unwanted chars with from end of the string str.rstrip(chars)

with open(filename, 'r') as fileobj:
    for row in fileobj:
        print( row.rstrip('\n') )

see also str.strip([chars]) and str.lstrip([chars])

(python >= 2.0)

The Answer 4

10 people think this answer is useful
temp = open(filename,'r').read().splitlines()

The Answer 5

9 people think this answer is useful

I think this is the best option.

temp = [line.strip() for line in file.readlines()]

The Answer 6

2 people think this answer is useful

Try this:


The Answer 7

-1 people think this answer is useful
my_file = open("first_file.txt", "r")
for line in my_file.readlines():
    if line[-1:] == "\n":

The Answer 8

-3 people think this answer is useful
import csv

with open(filename) as f:
    csvreader = csv.reader(f)
    for line in csvreader:

The Answer 9

-8 people think this answer is useful
def getText():
    for x,word in enumerate(names):
            return 0;
            print "length of ",word,"is over 20"
            return 0;
        return names;

def show(names):
    for word in names:
        print word," ",len_set

for i in range(1):


Add a Comment