truncate()

truncate(limit)
limit : (optional) upper limit of resizing the file.
If limit is not given the the truncate() works from the current position of file object.

Using mode 'a'

fob=open('data.txt','a')
fob.truncate()
fob.close()
# read the file
fob=open('data.txt','r')
print(fob.read())
Output is here ( used the data.txt file given at file read() )
This is first line
This is second line
This is third line
This is fourth line
In the above code we have not used limit so in mode = 'a' file pointer remains at the end of the file. So no data is truncated.

Using limit

fob=open('data.txt','a')
fob.truncate(13)
fob.close()
# read the file
fob=open('data.txt','r')
print(fob.read()) # This is first

using mode 'r'

We can't use mode 'r', this will generate error message.

using mode 'w'

When mode is ‘w’ file pointer remains at the beginning of the file to overwrite the content, hence there is no difference in using truncate() in this mode.
fob=open('data.txt','w')
fob.truncate(10)
fob.close()
# read the file
fob=open('data.txt','r')
print(fob.read())
writable()

File Append File Write


Subscribe to our YouTube Channel here



plus2net.com







Python Video Tutorials
Python SQLite Video Tutorials
Python MySQL Video Tutorials
Python Tkinter Video Tutorials
✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer