file.readlines留空行 [英] file.readlines leaving blank lines

查看:287
本文介绍了file.readlines留空行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经阅读到file.readlines逐行读取整个文件并将其存储在列表中. 如果我有这样的文件-

I have read that file.readlines reads the whole file line by line and stores it in a list. If I have a file like so -

Sentence 1
Sentence 2
Sentence 3

,我用readlines像这样打印每个句子-

and I use readlines to print each sentence like so -

file = open("test.txt") 
for i in file.readlines():
    print i

输出为

Sentence 1

Sentence 2

Sentence 3

我的问题是,为什么我要在每个句子之间加上额外的界线,又该如何去除呢?

My question is why do I get the extra line between each sentence and how can I get rid of it?

更新

我发现使用i.strip也会删除多余的行.为什么会这样?据我所知,split删除字符串末尾的空白.

I found that using i.strip also removes the extra lines. Why does this happen? As far as I know, split removes the white spaces at the end and beginning of a string.

推荐答案

file.readlines()返回字符串列表.每个字符串都包含尾随换行符. print语句用newlnie打印传递的参数.这就是为什么您需要额外的行.

file.readlines() return list of strings. Each string contain trailing newlines. print statement prints the passed parameter with newlnie.; That's why you got extra lines.

要删除多余的换行符,请使用str.rstrip:

To remove extra newline, use str.rstrip:

print i.rstrip('\n')

或使用sys.stdout.write

sys.stdout.write(i)

顺便说一句,除非您一次需要所有行,否则请不要使用file.readlines.只需迭代文件即可.

BTW, don't use file.readlines unless you need all lines at once. Just iterate the file.

with open("test.txt") as f:
    for i in f:
        print i.rstrip('\n')
        ...

更新

在Python 3中,为防止print打印尾随换行符,可以使用print(i, end='').

In Python 3, to prevent print prints trailing newline, you can use print(i, end='').

在Python 2中,您可以使用相同的功能: from __future__ import print_function

In Python 2, you can use same feature if you do : from __future__ import print_function

答案更新

制表符,换行符也被视为空格.

Tabs, Newlines are also considers as whitespaces.

>> ' \r\n\t\v'.isspace()
True

这篇关于file.readlines留空行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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