0

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() 
1
  • Side-note: for line in file: is almost always better than using for line in file.readlines():; the latter slurps the whole file into memory as a list of lines, requiring peak memory proportionate to the size of the whole file, and delaying processing until the entire file is read; the former lazily reads on-demand, requiring a roughly fixed amount of memory while allowing processing to begin while giving the OS time to cache the rest of the file (making it possibly faster, as well as requiring less memory). Commented Jul 7, 2020 at 0:03

1 Answer 1

1

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="")
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.