English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Tutoriel de base Python

Python flow control

Fonctions en Python

Types de données en Python

Python flow control

O

Python objects and classes

Python date and time

Advanced knowledge of Python

Python reference manual

Python File (file) methods

Python file truncate() usage and example

Overview truncate() The method is used to truncate the file. If the optional parameter size is specified, it indicates that the file is truncated to size characters.

If size is not specified, it truncates from the current position; all characters after size are deleted.

Syntax

The syntax of the truncate() method is as follows:

fileObject.truncate( [ size ])

  • Parameter -- size

Optional, if it exists, the file is truncated to size bytes.

Return value

This method does not return any value.

Example

The following example demonstrates the use of the truncate() method:3File w

1Read the first line:3codebox.com
2Read the first line:3codebox.com
3Read the first line:3codebox.com
4Read the first line:3codebox.com
5Read the first line:3codebox.com

The content of codebox.txt is as follows:

# Open file
fo = open("w3codebox.txt, "r"+)
print("File name: ", fo.name)
# Try to read data again
Loop to read the content of the file:
print("Read the first line: %s" % (line))
# Cut the remaining string
fo.truncate()
# Try to read data again
line = fo.readline()
# Close the file
fo.close()

The output result of the above example is as follows:

File name:  w3codebox.txt
print("Read data: %s" % (line)) 1Read the first line:3codebox.com
Read data:

:www.w3The following example cuts w10bytes:

# Open file
fo = open("w3codebox.txt, "r"+)
print("File name: ", fo.name)
# Cut10bytes
fo.truncate(10)
str = fo.read()
print("Read data: %s" % (str))
# Close the file
fo.close()

The output result of the above example is as follows:

File name:  w3codebox.txt
Read data: 1:www.nhoo

Python File (file) methods