to read line from file without getting "\n" appended at the end

POOJA GUPTA picture POOJA GUPTA · Jul 1, 2012 · Viewed 69.1k times · Source

My file is "xml.txt" with following contents:

books.xml 
news.xml
mix.xml

if I use readline() function it appends "\n" at the name of all the files which is an error because I want to open the files contained within the xml.txt. I wrote this:

fo = open("xml.tx","r")
for i in range(count.__len__()): #here count is one of may arrays that i'm using
    file = fo.readline()
    find_root(file) # here find_root is my own created function not displayed here

error encountered on running this code:

IOError: [Errno 2] No such file or directory: 'books.xml\n'

Answer

user25148 picture user25148 · Jul 1, 2012

To remove just the newline at the end:

line = line.rstrip('\n')

The reason readline keeps the newline character is so you can distinguish between an empty line (has the newline) and the end of the file (empty string).