Python file Truncate () method

Source: Internet
Author: User
Tags truncated

Overview

The Python file truncate () method is used to truncate the file and return the truncated byte length.

If the length is specified, the specified length is truncated from the beginning of the file, the remainder is deleted, and if the length is not specified, it is truncated from the beginning of the file to the current location and the remainder is deleted.

Grammar

The truncate () method syntax is as follows:

Fileobject.truncate ([size])
Parameters
    • size --optional, if present, the file is truncated from the beginning to the specified byte.

return value

The method has no return value.

Instance

The following example demonstrates the use of the Truncate () method:

The contents of the file Runoob.txt are as follows:

1:www.runoob.com2:www.runoob.com3:www.runoob.com4:www.runoob.com5:www.runoob.com

To iterate through the contents of a file:

#!/usr/bin/python3fo = open ("Runoob.txt", "r+", encoding= "Utf-8") # print ("File name:", Fo.name) Fo.seek (+) fo.truncate () # Removed everything from the 36th byte Fo.seek (0) line = Fo.readlines () print ("Read row:%s"% (lines)) Fo.truncate (10) # Intercept 10 bytes fo.seek (0) str = Fo.read () print ("Read data:%s"% (str)) # Close file Fo.close ()

The result of the above example output is:

File name:  runoob.txt Read line: [' 1:www.runoob.com\n ', ' 2:www.runoob.com\n '] read data: 1:www.runo

Python file Truncate () method

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.