I’m trying to read lines from a file and print them in a loop which works, but I get newlines after every print statement.
Here is my class
class FileReader:
"""Reads a file from args"""
def __init__(self, args):
input = ''
with open(args, 'r') as rFile:
for line in rFile:
print(line)
My input file is like this. (The ‘$’s are new lines):
12 3$
2$
9$
5$
3 4$
My output becomes:
12 3
2
9
5
3 4
What is the reason I’m getting those spaces?
When you loop over a file, the lines yielded include the newline at the end of the line. Using
print()outputs those lines with an extra newline.You can use
.strip()to remove whitespace from the start and end of the line, including the newline.If you only want to remove the newline at the end, use
line[:-1]orline.rstrip('\n')to remove it.Last but not least, you can also tell
print()not to add a newline: