+ 3
Help me with file project
file = open("/usercode/files/books.txt", "r") #your code goes here for i in range(1,5): print(file.read(1),len(file.readlines(i))) file.close()
3 Answers
+ 4
Daniel Kagombe ,
there are some issues in the code so here are some hints how to get it run:
file = open("/usercode/files/books.txt", "r") # ok
#for i in range(1,5): do not use this (1)
for i in file: # (1)
#print(file.read(1),len(file.readlines(i))) do not use this
# (2)
file.close() # ok
(1) we can not use a range to iterate on a file. but we can iterate on the file object. in each iteration cycle one line of the file will be stored in the varuable "i".
(2) for output we can now use:
> the variable name with the index for the first character (index starts with 0)
> the variable name with the len() function, to get the required length of the string
> attention: each line read from the file (except tge last line) has a trailing "new-line" sequence "\n", that
unfortunately also counts for the length
> to remove this, we can use the strip() function before getting the length
happy coding!
+ 2
Please read carefully the task description.
+ 1
Thankyou