Hey there, Could somebody help? What is wrong? file = open("/usercode/files/books.txt", "r") for line in file: print(line[0], len(line)) file.close()
7/14/2021 6:51:10 AM
Вито Грито9 Answers
New AnswerIs this what you were trying to do? file = open("/usercode/files/books.txt", "r") for line in file: print(f"{line[0]}{len(line)}") file.close()
Hi! try this: with open("/usercode/files/books.txt", "r") as f: line = f.readline() if not line: break print(f"{line[0]}{len(line)}") The "with ... as" part is called a context manager, it closes your file no matter what happens. It also saves you the file.close() part. You need to read the line with f.readline(). Afterward, you check if the end of the file is reached. The if-statement does so and breaks the while-loop. Have a great day!
Or this with open("/usercode/files/books.txt") as file: for title in file.readlines(): print(title[0] + str(len(title.strip("\n"))))
Вито Грито This part of the challenge is very important: Recall the readlines() method, which returns a list containing the lines of the file. Also, remember that all lines, except the last one, contain a \n at the end, which should not be included in the character count.
You are very welcome. I think you would help us when you mark the correct answer and maybe giving some "UPs" for good answers ;-)
Sololearn Inc.
535 Mission Street, Suite 1591Send us a message