+ 1

Project 5 Phyton Core

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()

14th Jul 2021, 6:51 AM
Вито Грито
9 odpowiedzi
+ 2
Is 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()
14th Jul 2021, 7:15 AM
Rik Wittkopp
Rik Wittkopp - avatar
+ 2
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!
14th Jul 2021, 7:36 AM
Zen Coding
Zen Coding - avatar
+ 2
Thank you guys!)
14th Jul 2021, 7:48 AM
Вито Грито
+ 2
Or this with open("/usercode/files/books.txt") as file: for title in file.readlines(): print(title[0] + str(len(title.strip("\n"))))
14th Jul 2021, 8:55 AM
David Ashton
David Ashton - avatar
+ 1
Try running the code I posted already
14th Jul 2021, 7:17 AM
Rik Wittkopp
Rik Wittkopp - avatar
+ 1
Sure, Just first time)
14th Jul 2021, 8:12 AM
Вито Грито
+ 1
Вито Грито 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.
14th Jul 2021, 8:13 AM
Rik Wittkopp
Rik Wittkopp - avatar
0
Need to print just first letter from each line + quantity of letters in each line
14th Jul 2021, 7:16 AM
Вито Грито
0
You are very welcome. I think you would help us when you mark the correct answer and maybe giving some "UPs" for good answers ;-)
14th Jul 2021, 7:58 AM
Zen Coding
Zen Coding - avatar