+ 1
In the given code, whichever block i place first sequentially returns a result while the one i place [continued in desc]
[continuation]- second returns the result as zero, why and how do make both read functions work with the same file name? #code: myfile=open(r'C:\Users\win8\Documents\Cs Record\trust.txt','r') #number of lines in the file: r2=myfile.readlines() nol=len(r2) print('The number of lines in trust.txt is',nol) #size of the file: r1=myfile.read() sof=len(r1) print('The size of trust.txt is',sof,'bytes') myfile.close()
2 Respostas
+ 3
If you need to re-read a file, you can either close it and re-open it, or seek() it to the beginning.
r2 = myfile.readlines()
nol = len(r2)
print('The number of lines in trust.txt is', nol)
# seek() it to the beginning
myfile.seek(0)
r1 = myfile.read()
sof = len(r1)
print('The size of trust.txt is', sof, 'bytes')
myfile.close()
https://docs.python.org/3/tutorial/inputoutput.html#methods-of-file-objects
+ 2
Thanks!, I made it work by closing and opening the file again in the middle but was wondering if there was any other method. The seek() function looks like what I was looking for.