10 Answers
New AnswerProblem: 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. My attempt is below. I’m lost about how to get the first element from the list generated. I end up with a list of strings instead of a string of characters.
4/10/2021 10:47:59 PM
Fan Mason10 Answers
New AnswerIf you just want the first n characters of the file (not n characters per line of the file), then you can just use; file.read()[:n] This will include any invisible or whitespace characters such as '\n'
file = open("/usercode/files/books.txt") n = int(input()) g=file.read()[:n] file.close() print(g) I think i had the join in there unnecessarily
CarrieForle FYI, file.read(n) will return n bytes of the file. Which in this particular case is ok (file uses default unicode type UTF-8), but could result in an issue if the unicode type in the file was larger. Also, just to be forthcoming, I'm not sure that the way I wrote it would give a different result if the unicode type was a larger type. At least not without doing some research and testing.
You iterated file.readlines(). You will get the list of strings. So don't use for loop, and use read instead. file.read(n)
file = open("/usercode/files/books.txt") n = int(input()) for i in file.readlines(): print(''.join(i[:n])) file.close()
file = open("/usercode/files/books.txt") #your code goes here n = int(input()) print(file.read()[:n]) file.close() I think this will work.)
Sololearn Inc.
535 Mission Street, Suite 1591Send us a message