+ 1
Inability to determine the length of the last line of the file
Hello, in the following code, I want to show the first character of each line of the file plus the length of that line. I do not know ,why in the last line, my output length is lower than the real length by 1? https://code.sololearn.com/cgaIHVdNKCZz/?ref=app
2 ответов
+ 1
'''
Mohammad Reza Moravejolahkami
It seems the last line have does not have an '\n'. So don't use len(line) -1.
Instead, use rstrip('\n' ) to temove the newline characters if they are present.
try this:
'''
with open("/usercode/files/books.txt", "r") as file:
for line in file:
x = len(line.rstrip('\n'))
print(line[0]+str(x))
+ 1
You can it read in in the task description.