Python program prints an extra empty line when rea

2020-04-29 09:47发布

问题:

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.

The text file looks like this:

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

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

>>
P,Pandora,32

>>

And the code is here:

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.

回答1:

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

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='')

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


回答2:

print adds \n and \r at the end of the string, and considering the line you've read already has a new line at the end, that's the behaviour. You can use instead:

print(line, end="")

Hope this helps!



回答3:

You can also use the "strip()" method that removes excess whitespace. In your case:
print(line.strip())

Or done with an assignment:
line = line.strip()
print(line)



回答4:

If you want to remove the trailing new line of the string, you can use rstrip('\n'):

print line.rstrip('\n')