0

Python working with files reading through

DoES NOT WORK HERE IS THE DESCRIPTION You need to make a program to read the given number of characters of a file. Take a number N as input and output the first N characters of the books.txt file.

17th Feb 2021, 7:16 AM
Kim Hammar-Milliner
Kim Hammar-Milliner - avatar
5 odpowiedzi
+ 2
Kim Hammar-Milliner That is because the last line of the file has no trailing new line or "\n". You can use line.strip() to remove the "\n" then use len function (without -1). Or another method is to use if-else condition, if "\n" is at the end of the line, get the lenght subtracted by 1, otherwise just get the length.
17th Feb 2021, 8:38 AM
noteve
noteve - avatar
0
my code 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() all the test cases fails
17th Feb 2021, 7:17 AM
Kim Hammar-Milliner
Kim Hammar-Milliner - avatar
0
Noura moussa
17th Feb 2021, 6:08 PM
Noura Moussa
Noura Moussa - avatar
0
How are you today to see you tomorrow morning how are
17th Feb 2021, 6:09 PM
Noura Moussa
Noura Moussa - avatar
0
file = open("/usercode/files/books.txt") #your code goes here n = int(input()) print(file.read(n)) file.close()
29th Jul 2021, 4:50 PM
Rares-Vasile Irimus
Rares-Vasile Irimus - avatar