Assume you have a file called letters.txt containing all the lowercase letters of the alphabet in order one letter per line. What would be printed out by the following code?
f = open("letters.txt") info = f.readline() print(len(info)) f.close()
f = open("letters.txt") info = f.readline() info = f.readline() print(info[0]) f.close()
f = open("letters.txt") info = f.readline() f.close() f = open("letters.txt") info = f.readline() print(info[0]) f.close()
f = open("letters.txt")
info = f.readline()
print(len(info))
f.close()
Python file readline() method reads one entire line in a file including the newline character('\n').
So, here the output of print() statement will be the length of characters read from the first line, i.e., 2(which is the single alphabet read and '\n' symbol).
f = open("letters.txt")
info = f.readline()
info = f.readline()
print(info[0])
f.close()
Here, the readline() method is called twice. For first call, info variable stores 'q\n' and for second call, info variable stores 'w\n'. So, the recent value stored will be used and info[0] gives the ouput as 'w'.
f = open("letters.txt")
info = f.readline()
f.close()
Here, the required file is simply opened and read and the 1st line data is stored in info variable.
f = open("letters.txt")
info = f.readline()
print(info[0])
f.close()
Here, the 1st line data is stored, i.e., 'q\n'. And, info[0] gives output 'q'.
letters.text sample file: -
q
w
e
r
t
y
u
i
o
p
a
s
d
f
g
h
j
k
l
m
n
b
v
c
x
z
Get Answers For Free
Most questions answered within 1 hours.