YouTip LogoYouTip

Python3 File Truncate

# Python3.x Python3 File truncate() Method [![Image 3: Python3 File Methods](#) Python3 File Methods](#) * * * ### Overview The **truncate()** method is used to truncate the file from the first byte of the first line, truncating the file to size bytes. If size is not specified, it truncates from the current position; after truncation, all bytes after V are deleted. Note that a line break on Windows represents 2 bytes. ### Syntax The syntax for the truncate() method is as follows: fileObject.truncate( ) ### Parameters * **size** -- Optional. If present, the file is truncated to size bytes. ### Return Value This method does not return a value. ### Example The following examples demonstrate the use of the truncate() method: The content of the file tutorial.txt is as follows: 1:www. 2:www. 3:www. 4:www. 5:www. Loop to read the file content: #!/usr/bin/python3 fo = open("tutorial.txt", "r+")print ("Filename: ", fo.name) line = fo.readline()print ("Read line: %s" % (line)) fo.truncate() line = fo.readlines()print ("Read line: %s" % (line))# Close the file fo.close() The output of the above example is: Filename: tutorial.txt Read line: 1:www. Read line: ['2:example.comn', '3:example.comn', '4:example.comn', '5:example.comn'] The following example truncates the tutorial.txt file to 10 bytes: #!/usr/bin/python3# Open the file fo = open("tutorial.txt", "r+")print ("Filename: ", fo.name)# Truncate to 10 bytes fo.truncate(10) str = fo.read()print ("Read data: %s" % (str))# Close the file fo.close() The output of the above example is: Filename: tutorial.txt Read data: 1:www.runo * * Python3 File Methods](#)
← Python3 File WritelinesPython3 File Truncate β†’