从文件中读取行而不会得到"\ n"附加在末尾 [英] to read line from file without getting "\n" appended at the end
本文介绍了从文件中读取行而不会得到"\ n"附加在末尾的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的文件是"xml.txt",具有以下内容:
My file is "xml.txt" with following contents:
books.xml
news.xml
mix.xml
如果我使用readline()函数,它将在所有文件的名称后附加"\ n",这是一个错误,因为我想打开xml.txt中包含的文件.我是这样写的:
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'
推荐答案
要在结尾处仅删除换行符:
To remove just the newline at the end:
line = line.rstrip('\n')
readline
保留换行符的原因是,您可以区分空白行(具有换行符)和文件末尾(空字符串).
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).
这篇关于从文件中读取行而不会得到"\ n"附加在末尾的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文