从Python中的文件中读取行而不会得到“\ n”附在最后 [英] to read line from file in python without getting "\n" appended at the end
问题描述
我的文件是xml.txt,内容如下:
books.xml
news.xml
mix.xml
如果使用readline()函数,它附加\\\
at所有文件的名称,因为我想打开xml.txt中包含的文件是错误的。我写了这个:
$ $ p $ fo = open(xml.tx,r)
(count .__ len __()):#here count是可能数组之一,我使用
file = fo.readline()
find_root(file)#这里find_root是我自己创建的函数不显示这里
运行此代码时遇到错误:
< IOError:[Errno 2] No such file or directory:'books.xml\\\
'
line = line.rstrip('\\\
')
$ b原因
readline
保持换行符,所以你可以区分一个空行(有换行符)和文件的结尾(空字符串)。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'
解决方案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).这篇关于从Python中的文件中读取行而不会得到“\ n”附在最后的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!