Working with Files: Intermediate Python | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Working with Files: Intermediate Python

"Working with Files You are given a books.txt file, which includes book titles, each on a separate line. Create a program to output how many words each title contains, in the following format: Line 1: 3 words Line 2: 5 words ... Make sure to match the above mentioned format in the output." I managed to found how many words each title contains, but I am having a trouble in identifying the lines in the format above. Here is my try: "with open("/usercode/files/books.txt") as f: cont = f.readlines() for line in cont: words = line.split() for line in list(cont): print('Line ' + str(cont.index(line)) + ': ' + str(len(words)) + ' words')" Can anybody help me? Thanks in advance

26th Nov 2021, 2:03 PM
ana alice
4 Answers
+ 5
Or maybe better with the enumerate() function: with open("/usercode/files/books.txt") as f: cont = f.readlines() for n, line in enumerate(cont): words = line.split() print('Line ' + str(n+1) + ': ' + str(len(words)) + ' words')
26th Nov 2021, 2:24 PM
Coding Cat
Coding Cat - avatar
+ 2
What is the 2. loop for? Maybe this is working as expected? with open("/usercode/files/books.txt") as f: cont = f.readlines() n = 0 for line in cont: words = line.split() n += 1 print('Line ' + str(n) + ': ' + str(len(words)) + ' words')
26th Nov 2021, 2:16 PM
Coding Cat
Coding Cat - avatar
+ 1
It worked!! Finally, I understood Thank you for your help :)
26th Nov 2021, 2:48 PM
ana alice
0
You're welcome.
26th Nov 2021, 2:51 PM
Coding Cat
Coding Cat - avatar