Python inserting new line when using print() inside a for loop

I am doing simple files exercises with Python (3.8 in Linux Mint 20, Ubuntu 20.04 based, Pycharm) and when I run this code the output is the expected but with new line inserted between each lines. Maybe it is simple to solve but, any help?

import os.path

def read_table():
    x = int(input("Enter a number between 1 and 10: "))
    if os.path.exists("tabla-{}.txt".format(x)):
        file = open("tabla-{}.txt".format(x), "r")
        for line in file.readlines():
            print (line)
    else:
        print("The file doesn't exist")

def main():
    read_table()

if __name__ == "__main__":
    main() 

Upvotes: 0

Views: 180

Answers (1)

raccoons
raccoons

Reputation: 420

print() has an end parameter that can be used to insert a string after printing. By default it is a \n (newline character) but if you want to get rid of that you can do

for line in file.readlines():
            print (line, end="")

Upvotes: 1

Related Questions