Error in file | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
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

23rd Oct 2020, 6:14 AM
Luciron
Luciron - avatar
6 Answers
+ 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 😊
23rd Oct 2020, 8:48 AM
Hacker Badshah
Hacker Badshah - avatar
+ 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.
23rd Oct 2020, 6:35 AM
ChaoticDawg
ChaoticDawg - avatar
0
Please link your code here
23rd Oct 2020, 6:15 AM
A S Raghuvanshi
A S Raghuvanshi - avatar
0
Ok
23rd Oct 2020, 6:17 AM
Luciron
Luciron - avatar
0
How to fix file?
23rd Oct 2020, 6:20 AM
Luciron
Luciron - avatar