john
john

Reputation: 49

How does file truncate works in python?

I have a simple question about truncating files in python. Let's say that I have a file called myfile.txt and I have inside the phrase hello what are you doing in one line.

First of all I open the file: f = open('c:/Users/User/Desktop/myfile.txt','r')

Then if I use f.truncate(5) and close the file it will change the file and inside it, will be hello. That means give me 5 bytes of the file no matter the position of the cursor (correct me if I am wrong). If I don't use any number in the truncate method ,it is going to delete everything inside the file. However if I read the file f.read(6) that means that the cursor is now at the position 6 (I can see that using f.tell()) and then I use f.truncate() then nothing happens to the file and nothing is changed. Why is that? I moved the cursor to positon 6 and then I use truncate... On w3schools, they say that if I don't put anything inside truncate then the current position will be used. What does that mean?

Upvotes: 1

Views: 1003

Answers (1)

Deck451
Deck451

Reputation: 61

Ran into the same problem, just now. Just open your file in 'r+b' mode.

For some reason I am still a bit unsure about, opening the file in binary mode caused truncate to work as described in the docs. Also don't forget to add the + mode too. It won't work for files open just for reading.

This isn't a singular case either. There are quite a few more file object methods that work as intended on files open in binary mode and less so on files open in the default text mode.

Anyway, hope that helps.

Upvotes: 1

Related Questions