Huzo
Huzo

Reputation: 1692

Reading lines in a file that end with \n

When I do

f = open("test.txt","r")
s = f.readline()
l = s.split[' ']

in which the input file has the content 2 3\n. s has the value ['2', '3\n']. Is there a way to tell python that each line ends with a \n and therefore it should not read it?

Contents of file:

3 2\n
#1###2#\n
****#**\n
##*###*\n
#******\n
#*#O##*\n

I will do other operations for the other lines. But I still need to get rid of \n

Upvotes: 0

Views: 736

Answers (1)

DeepSpace
DeepSpace

Reputation: 81604

The caveat here is that except for the literal '\n' there is also an actual \n at the end of each line (except for the last line, which only has the literal '\n'):

with open('test.txt') as f:
    print(f.readlines())
# ['3 2\\n\n', '#1###2#\\n\n', '****#**\\n\n', '##*###*\\n\n', '#******\\n\n', '#*#O##*\\n']

You need to call .strip with both the literal '\n' and the actual \n:

with open('test.txt') as f:
    lines = [line.strip('\\n\n') for line in f]

print(lines)
# ['3 2', '#1###2#', '****#**', '##*###*', '#******', '#*#O##*']

Upvotes: 1

Related Questions