+ 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.
15 Réponses
+ 5
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
+ 3
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
N = int(input())
print(file.read(N))
+ 1
file = open("/usercode/files/books.txt")
n = int(input())
for i in file.readlines():
print(''.join(i[:n]))
file.close()
+ 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
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.)
0
My Solution:
file = open("/usercode/files/books.txt")
#your code goes here
n = int(input())
g=file.read()[:n]
file.close()
print(g)
0
N = int(input("Enter the number of characters to read: "))
with open("books.txt", "r") as file:
content = file.read(N)
print(content)
0
file = open("filename.txt",'r')
char=int(input())
a=file.read(char)
print(a)
file.close()
0
My Solution:
file = open("/usercode/files/books.txt")
#your code goes here
N = int(input())
N = file.read(N)
print(N)
file.close()
0
This is my code
file = open("/usercode/files/books.txt")
#my code
N=int(input())
print(file.read(N))
file.close()