从Python中的文件中读取行而不会得到“\ n”附在最后 [英] to read line from file in python without getting "\n" appended at the end

查看:762
本文介绍了从Python中的文件中读取行而不会得到“\ n”附在最后的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的文件是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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆