读取文本文件时,Python程序会额外打印一行空行 [英] Python program prints an extra empty line when reading a text file

查看:199
本文介绍了读取文本文件时,Python程序会额外打印一行空行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用python 3.3.例如,我有一个包含三行文本的文本文件.我想选择一个数字,它将显示该行号的内容.由于某种原因,它会打印我想要的行,并在其下方打印一个空行.

I'm using python 3.3. I have a text file with three lines of text, as an example. I want to select a number and it will display the contents of that line number. For some reason, it prints the line I want, and prints an empty line below it.

文本文件如下所示:

AAPL,Apple,700
P,Pandora,32
MW,Men's Warehouse,54.32

如果我是2,我得到的解释器中的输出:

The output in the interpreter I get if i is 2:

>>
P,Pandora,32

>>

代码在这里:

line_number = int(input('Enter the line number: '))
with open('C:/Python33/myprogramtests/filewrite1.txt') as f:
    i = 1
    for line in f:
        if i == line_number:
            break
        i += 1
    print (line)

我在打印(行)后确实尝试了逗号,但是没有用. 我猜想我丢失了一些只打印该行而不是多余的空白行的代码.

I did try a comma after print (line) but it didn't work. I'm guessing I'm missing some bit of code that would print just the line and not an extra whitespace line.

推荐答案

您应该为print提供end='',以禁止在输出中添加等价于\n的自动行为.

You should provide an end='' to print to suppress the automatic behaviour of adding the equivalent of \n to output.

我还将删除计数逻辑,并使用islice提取所需的行,例如:

I'd also remove the counting logic and use islice to extract the line you wish, eg:

from itertools import islice

line_number = int(input('Enter the line number: '))
with open('yourfile') as fin:
    print(next(islice(fin, line_number - 1, line_number), ''), end='')

如果要使用计数方法,则可以使用从1开始的enumerate,例如:

If you wanted to use the count approach, then you can use enumerate starting at 1, eg:

for idx, line in enumerate(fin, start=1):
    if idx == line_number:
        print(line, end='')
        break

这篇关于读取文本文件时,Python程序会额外打印一行空行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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