Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python program prints an extra empty line when reading a text file

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.

like image 511
user2859603 Avatar asked Mar 15 '26 13:03

user2859603


2 Answers

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
like image 100
Jon Clements Avatar answered Mar 18 '26 03:03

Jon Clements


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!

like image 22
cdonts Avatar answered Mar 18 '26 02:03

cdonts



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!