Python program prints an extra empty line when reading a text file
Question: 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.


Answer: 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
    

