+ 3
problem with write method !
file = open(“sampleText.txt”, “w”) file.write(“hello Sololearn “) print(file.write()) why write method in 3rd line is not showing the length of total bytes written in 2nd line ?
15 Réponses
+ 8
A͢J ,
the explanation of file.tell() that it returns the length (of what ?) can be misunderstood. it is correct in some cases, but not in all. this is what the python docs are saying:
file.tell() returns an integer giving the file object’s current position in the file represented as number of bytes from the beginning of the file when in binary mode and an opaque number when in text mode.
this means that it shows the current position of the file pointer in the in the current file object.
+ 6
Sandeep ,
the filepointer, its use and behavior is the same in all programming languages.
let's compare 2 files: `file_with_text.txt` (contains several lines of text) and `file_empty.txt`.
open both files and call tell(). both will result 0. this does not say anything about the length of the total file or the length of a line of the file.
use .seek(0, 2) to place the file pointer to the end of the file. use tell() again.
`file_empty.txt` will return 0, since beginn and end of the file are the same position.
`file_with_text.txt` will return an integer number, which is the position of the file pointer, that indicates also the number of bytes counted from
the beginn of the file upto the current position.
+ 5
Lothar won't it be same as length always?
what are some incorrect cases?
+ 5
Sandeep ,
(1) if need to know the size of a file, we do not need to open the file. here is a link to various versions of getting the file size:
https://www.geeksforgeeks.org/how-to-get-file-size-in-JUMP_LINK__&&__python__&&__JUMP_LINK/
(2) what we can do to get the numer of bytes that have been currently written to a file:
with open('sampleText99.txt', 'w') as file:
print(file.write('hello Sololearn ')) # result 16
print(file.write('abc')) #result 3
+ 5
Lothar thanks! 🙌
+ 4
Fasabbi
Use the Q/A for queries because there are some problems in Sololearn msg box + chances of you getting an answer fast will be increased if you use q/a
+ 3
A͢J thanks a lot
+ 3
Lothar So, it's not useful in getting the length of a file but in case of writing to a file, this can be used without any problem? or it should be avoided?
+ 3
Sandeep drop ur most active social media
+ 3
Fasabbi i am most active on sololearn only. Q/A is the best way to learn and as mentioned earlier, chances of learning from more people is better than chance of learning from one
+ 3
The write() method writes data to a file and returns the number of bytes of written data, it must have one argument.
+ 2
Fasabbi
write method accept 1 argument so you will get error on 3rd line.
use tell() method to get length
print(file.tell())
+ 1
Okay
- 2
Can I have anyone WhatsApp number