[python] How to read a file without newlines?

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?

This question is related to python line-breaks readlines

The answer is


Try this:

u=open("url.txt","r")  
url=u.read().replace('\n','')  
print(url)  

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)


my_file = open("first_file.txt", "r")
for line in my_file.readlines():
    if line[-1:] == "\n":
        print(line[:-1])
    else:
        print(line)
my_file.close() 

temp = open(filename,'r').read().split('\n')

import csv

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

def getText():
    file=open("ex1.txt","r");

    names=file.read().split("\n");
    for x,word in enumerate(names):
        if(len(word)>=20):
            return 0;
            print "length of ",word,"is over 20"
            break;
        if(x==20):
            return 0;
            break;
    else:
        return names;


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


for i in range(1):

    names=getText();
    if(names!=0):
        show(names);
    else:
        break;

I think this is the best option.

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

temp = open(filename,'r').read().splitlines()