Python os.truncate()
Python os.truncate()方法截断与path对应的文件,使其大小不超过长度字节。这个函数也可以支持文件描述符。
语法:os.truncate(path, length)
参数:
path:该参数是要被截断文件的路径或文件描述符。
length:这是要截断的文件的长度。
返回值:此方法不返回任何值。
示例1
使用os.truncate()方法使用文件的路径截断文件。
# Python program to explain os.truncate() method
# importing os module
import os
# path
path = 'C:/Users/Rajnish/Desktop/testfile.txt'
# Open the file and get
# the file descriptor associated
# with it using os.open() method
fd = os.open(path, os.O_RDWR|os.O_CREAT)
# String to be written
s = 'GeeksforGeeks - A Computer Science portal'
# Convert the string to bytes
line = str.encode(s)
# Write the bytestring to the file
# associated with the file
# descriptor fd
os.write(fd, line)
# Using os.truncate() method
# Using path as parameter
os.truncate(path, 10)
# Seek the file from beginning
# using os.lseek() method
os.lseek(fd, 0, 0)
# Read the file
s = os.read(fd, 15)
# Print string
print(s)
# Close the file descriptor
os.close(fd)
输出:
b'GeeksforGe'
示例2
使用os.truncate()方法使用文件描述符截断文件
# Python program to explain os.truncate() method
# importing os module
import os
# path
path = 'C:/Users/Rajnish/Desktop/testfile.txt'
# Open the file and get
# the file descriptor associated
# with it using os.open() method
fd = os.open(path, os.O_RDWR|os.O_CREAT)
# String to be written
s = 'GeeksforGeeks'
# Convert the string to bytes
line = str.encode(s)
# Write the bytestring to the file
# associated with the file
# descriptor fd
os.write(fd, line)
# Using os.truncate() method
# Using fd as parameter
os.truncate(fd, 4)
# Seek the file from beginning
# using os.lseek() method
os.lseek(fd, 0, 0)
# Read the file
s = os.read(fd, 15)
# Print string
print(s)
# Close the file descriptor
os.close(fd)
输出:
b'Geek'