PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, November 2, 2022

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

 November 02, 2022     file, linux, python, readlines     No comments   

Issue

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. ']



Answered By - xFranko
Answer Checked By - David Goodson (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing