Python truncate() Function

The truncate() function in Python is used to truncate the size of a file. Basically the truncate() function is used to resize the file to given number of bytes.

For example, I've a file named codescracker.txt available in current directory for the Python program given below. The following snapshot shows that current directory along with opened file codescracker.txt:

python truncate function file

And the following snapshot shows the size of above file:

python truncate function file size

Now let's create a program, that truncate the size of this file to 120 bytes:

fob = open("codescracker.txt", "a")
fob.truncate(120)
fob.close()

After executing the above program, the size of file gets truncated. Now the size is 120 bytes. Here is the new snapshot that shows the properties of file:

python truncate function size of file

Python truncate() Function Syntax

The syntax of truncate() function in Python, is:

fileObject.truncate(size)

The size parameter is optional. Therefore if the size parameter is not specified, then the current position will be used. The default value of size is None.

Python truncate() Function Example

Here is an example of truncate() function in Python. This program allows user to create a file, and define the size of file, at run-time of the program:

print("Enter the Name of File: ", end="")
fileName = input()

fileObject = open(fileName, "a")

print("\nEnter the Size of File: ", end="")
sizeOfFile = int(input())

fileObject.truncate(sizeOfFile)
fileObject.close()

print("\nThe file '{}' is created of size '{}' bytes".format(fileName, sizeOfFile))

The snapshot given below shows the sample run of above program with user input myfile.txt as name of file and 2048 as total bytes as size to create a file of 2048 bytes or 2KB:

python truncate function

Now if you open the current directory, then a file with same name and size as provided in above sample run, will be available there.

Python Online Test


« Previous Function Next Function »


Liked this post? Share it!