Categories
Python Answers

How to get rid of \n when using .readlines() in Python?

Spread the love

Sometimes, we want to get rid of \n when using .readlines() in Python.

In this article, we’ll look at how to get rid of \n when using .readlines() in Python.

How to get rid of \n when using .readlines() in Python?

To get rid of \n when using .readlines() in Python, we call read with splitlines.

For instance, we write

with open(filename) as f:
    mylist = f.read().splitlines() 

to open the filename file with open.

Then we call read to read the file into an iterator with the lines in the filename file.

And then we call splitlines to split the lines into a list of line strings.

Conclusion

To get rid of \n when using .readlines() in Python, we call read with splitlines.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *