Reading Through: 35.2 Challenge Python For Data Science | Sololearn: Learn to code for FREE!

+1

Reading Through: 35.2 Challenge Python For Data Science

Problem: 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 Mason

9 Answers

New Answer

+2

If 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'

+2

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.

+2

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

+1

You iterated file.readlines(). You will get the list of strings. So don't use for loop, and use read instead. file.read(n)

0

file = open("/usercode/files/books.txt") n = int(input()) for i in file.readlines(): print(''.join(i[:n])) file.close()

0

Thanks all

0

Fan Mason what was your final code? Whats above doesnt seen to work. Thanks!

0

Thanks Fan Mason !!

0

file = open("/usercode/files/books.txt") #your code goes here n = int(input()) print(file.read()[:n]) file.close() I think this will work.)