+ 1

Can you please tell me what is wrong with this code

It should print the first word of every name in the list and length of that name but it only returns half of the list( the file is complete and only been reading) for n in file: list = file.readline() first_word = list.split()[0] length = len(list) print(first_word,length) Thanks 👍

1st May 2022, 8:40 PM
mh.S
mh.S - avatar
5 Answers
+ 1
'for n in file' already gets file lines - no need for an additional 'file.readline'. Those are probably disputing file lines, leaving half for each one.
2nd May 2022, 1:05 AM
Emerson Prado
Emerson Prado - avatar
+ 2
Try this: for line in file.readlines(): first_word = line.split()[0] ...
1st May 2022, 8:44 PM
Simon Sauter
Simon Sauter - avatar
+ 2
file = open('/usercode/files/books.txt') list = file.readlines() for n in list: first_line = list[0] print(first_line) file.close()
2nd May 2022, 7:08 AM
FꫀâČ…áƒ«á„†ÍŸá„™á„‰áŻœ
FꫀâČ…áƒ«á„†ÍŸá„™á„‰áŻœ - avatar
+ 2
#Book titles: with open('/home/files/books.txt') as f: x = f.readlines() f.close() for i in x: l = len(i[1:]) if l == 17: l = 18 s = i[0] print(f'{s}{l}')
2nd May 2022, 7:15 AM
FꫀâČ…áƒ«á„†ÍŸá„™á„‰áŻœ
FꫀâČ…áƒ«á„†ÍŸá„™á„‰áŻœ - avatar
0
Thank you all👍
2nd May 2022, 8:12 AM
mh.S
mh.S - avatar