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
.