0
Error in file
In file books.txt(question in Learn Program) writed 4 lines, but in answer writed 3 lines. What to fix that? code link: https://code.sololearn.com/c9yTGXPH4L3L/?ref=app
6 ответов
+ 1
Every line has \n except the last line in the file.
So you should use if statement to check if it has \n and then subtract 1
My Code:
file = open("/usercode/files/books.txt", "r")
#your code goes here
books = file.readlines()
for book in books:
if "\n" in book:
print(book[0]+str(len(book)-1))
else:
print(book[0]+str(len(book)))
file.close()
Hope It Helps You 😊
+ 1
Your current code is subtracting 1 from the last line in the file which doesn't have the last character of a newline '\n'. Try saving the lines of the file in a list using file.readlines() then loop over all but the last line and output the info as you are. Then, after the loop, output the info correctly for the last line without subtracting 1 from the line length.
0
Please link your code here
0
Ok
0
How to fix file?