pythonlinuxfilereadlines

How to skip the "\n" in the output while using the readlines() method?


I want to read a notepad file by using the readlines() method.

f = open('/home/user/Desktop/my_file', 'r')
print(f.readlines())

The output is: ['Hello!\n', 'Welcome to Barbara restaurant. \n', 'Here is the menu. \n']

As you see the newlines will be mentioned in the output, too. What should I do? Note that I want to use the readlines() method.

P.S! My operating system is Linux Ubuntu and here's the link to my file.

https://drive.google.com/file/d/1baVVxZjXmFwo_3uwdUCsrwHOG-Dlfo38/view?usp=sharing

I want to get the output below:

Hello!
Welcome to Barbara restaurant.
Here is the menu.

Solution

  • Update (Since you need the readlines() method)

    f = open('/home/user/Desktop/my_file', 'r')
    for line in f.readlines():
        print(line, end='')
    

    Output

    Hello!
    Welcome to Barbara restaurant.
    Here is the menu.
    

    Original

    You can read then split each line

    f = open('/home/user/Desktop/my_file', 'r')
    print(f.read().splitlines())
    

    Output

    ['Hello!', 'Welcome to Barbara restaurant. ', 'Here is the menu. ']