0

Removing \n from read files at unspecified location

Tried to use this code but doesn’t work to remove \n is there something wrong with it or another method. Cant find anything online. Please also explain how it works file = open("/usercode/files/books.txt", "r") list = file.readlines() print(list[0]) for i in list: list.replace("\n", " ") print(list)

3rd Jan 2022, 2:17 PM
Darkpidgeon 14
4 odpowiedzi
+ 1
1. list.replace("\n", " ") to i.replace("\n", " ") 2. replace return a new string object list = [i.replace("\n", " ") for i in list] 3. file.close() // at the end
3rd Jan 2022, 2:25 PM
FanYu
FanYu - avatar
+ 7
Check whether or not a line ends with '\n', if so, strip the '\n' off ... lst = file.readlines() for line in lst: if line.endswith( '\n' ): line = line.strip() print( line ) (Edited) Thanks Lothar for correction
3rd Jan 2022, 2:50 PM
Ipang
+ 5
Ipang , there is a typo in the first line. there is dot missing. should be: lst = file.readlines() ^
3rd Jan 2022, 4:51 PM
Lothar
Lothar - avatar
0
fan yu thank you
3rd Jan 2022, 2:52 PM
Darkpidgeon 14