skip to Main Content

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.

2

Answers


  1. 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. ‘]

    Login or Signup to reply.
  2. A pipelined approach going trough every line once on demand. This can be more memory friendly with the downside of being a bite more complicated.

    f = open('/home/user/Desktop/my_file', 'r')
    
    lines_iter = map(str.strip, f)  # note you can only go through this once!
    lines = list(lines_iter)        # optional: move everything to a list
    
    f.close() # don't forget to close - but only AFTER using the map object
    

    Output –

    >>> print(lines)
    ['Hello!', 'Welcome to Barbara restaurant.', 'Here is the menu.']
    >>> print("n".join(lines))
    Hello!
    Welcome to Barbara restaurant.
    Here is the menu.
    

    Depending on the usage you don’t need to move it into a list.
    But the file object needs to be accessible until the map object worked over it.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search