+ 2

"Book titles" problem

Hello to everyone! I'm new and I'm just learning Python, so please forgive me if I say something wrong/strange. I saw how to resolve this problem in a fastest way, but I wanted to solve it in my way. I wrote this code. As you can see I used a quick command to count the elements in the file (viewed as a list) and used that count to run the "for loop". The foor loop wasn't a big deal, my question is on that "x" variable. Is there a easier/fastest way to do the same without closing and reopening the file? I'm scared that in a biggest code too much open/close would slow down the program. ------------------------------------------------------------------------------------------------------------- CODE STARTS HERE file = open("/usercode/files/books.txt", "r") x = len(list(file)) file.close() file = open("/usercode/files/books.txt", "r") i = 0 for line in file: if i < x : print(line[0] + str(len(line)-1)) else: print(line[0]+str(len(line))) break i+=1 ----------------------------------------------------------------- Thank you for any advice and for the help :)

1st Sep 2021, 5:15 PM
Alvise Fortin
Alvise Fortin - avatar
1 ответ
+ 7
the shortest way would be this: for line in open("/usercode/files/books.txt", "r"): print(line[0] + str(len(line.strip()))) the strip() method does remove leading and trailing whitespaces, this includes new-line characters.
1st Sep 2021, 6:40 PM
Lothar
Lothar - avatar