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. It truncates the file to `size` bytes. If `size` is not provided, it truncates from the current position. After truncation, all bytes after the truncation point are deleted. Note that on Windows systems, a newline character 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 ("File Name: ", 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: File Name: 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 ("File Name: ", 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: File Name: tutorial.txt Read Data: 1:www.runo * * Python3 File Methods](#)
← Python3 File TruncatePython3 File Seek β†’