I am a new to python programming. I've followed the "Learn python the hard way" book but that is based on python 2x.
def print_one_line(line_number,f):
print(line_number,f.readline())
In this function every time it prints A line and a new line.
1 gdfgty
2 yrty
3 l
I read the documentary that if i put a , (comma) after readline() then it won't print a new \n. Here is the documentary:
Why are there empty lines between the lines in the file? The readline() function returns the \n that's in the file at the end of that line. This means that print's \n is being added to the one already returned by readline() fuction. To change this behavior simply add a , (comma) at the end of print so that it doesn't print its own .
When I run the file with python 2x then it is OK, but when I do it in python 3x then the newline is printed. How to avoid that newline in python 3x?
Since your content already contains the newlines you want, tell the print()
function not to add any by using the optional end
argument:
def print_one_line(line_number,f):
print(line_number,f.readline(), end='')
Beside the other ways, you could also use:
import sys
sys.stdout.write(f.readline())
Works with every Python version to date.
Rather than skipping the newline on output, you can strip it from the input:
print(line_number, f.readline().rstrip('\n'))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With