Python – remove newline from readlines

 

readlines() is a function in python used to read text file and convert it into list where each line in at file is a element in list with new line(\n) at the end of each element.

Example:

>>> filelist = open("file.txt").readlines()
['a\n', 'b\n', 'c\n', 'd\n']

If you want to remove new line(\n) at the end of all elements in list use read() and splitlines() functions as shown in below example.

read().splitlines() will do same funcationality as readlines() & only difference is read().splitlines() won’t have have new line(‘\n’) at the end of all elements in list.

Example:

>>>open("file.txt").read().splitlines()
['a', 'b', 'c', 'd']

Leave a comment