Intermediate python working with files | Sololearn: Learn to code for FREE!

+1

Intermediate python working with files

soRRY ABOUT THE CAPS BUT MY DEVICE WONT TURN THENCAPS OFF IM STUCK FOR THE THREE LESSONS READING THROUGH BOOK CLUB FILLINGBUP WITH NUMBERS THEY ARE FAILING ON ALL CASES BOOK CLUB file = open("/usercode/files/books.txt", "r") for line in file: nums= list(line) x=len(nums)-1 print(line[0]+str(x)) file.close()

2/17/2021 7:05:25 AM

Kim Hammar-Milliner

7 Answers

New Answer

+2

I have an answer on your other similar thread. https://www.sololearn.com/Discuss/2699121/?ref=app

+1

here is the description 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.

+1

I have made it! line_num = 0 with open("/usercode/files/books.txt") as f: for line in f.readlines(): line_num += 1 print("Line"+" "+str(line_num)+":"+" "+str(len(line.split()))+" "+"words") f.close()

+1

A little tweak on Swapnil Kamdi's code, it is correct, but you don't have to + on spaces, spaces inside Quotation mark does count. Example: print("Line"+" "+str(line_num)+":"+" "+str(len(line.split()))+" "+"words") Tweaked example: print("Line " + str(line_num) + ": " + str(len(line.split())) + " words") Note: Not that big of a deal, but could make the code easier to read. Tweaked code: line_num = 0 with open("/usercode/files/books.txt") as f: for line in f.readlines(): line_num += 1 print("Line " + str(line_num) + ": " + str(len(line.split())) + " words") f.close()

+1

with open("/usercode/files/books.txt") as f: #your code goes here for count, line in enumerate(f.readlines()): print(f'Line {str(count+1)}: {str(len(line.split()))} words')

0

not sure how to do line 1: h12 and the other three lines

0

line_num = 0 with open("/usercode/files/books.txt") as f: for line in f.readlines(): line_num += 1 print("Line"+" "+str(line_num)+":"+" "+str(len(line.split()))+" "+"words") f.close()