当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Python os.ftruncate()用法及代码示例


操作系统模块Python中的Windows提供了与操作系统进行交互的函数。操作系统属于Python的标准实用程序模块。该模块提供了使用依赖于操作系统的函数的便携式方法。
os.ftruncate()方法将截断与文件描述符fd对应的文件,因此该文件最大为字节大小。

用法: os.ftruncate(fd, length)

参数:
fd: 这是将被截断的文件描述符。
length: 这是要截断的文件的长度。


返回值:此方法不返回任何值。

示例1:
使用os.ftruncate()截断文件的方法

# Python program to explain os.ftruncate() 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.ftruncate() method 
os.ftruncate(fd, 5) 
  
# 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'Geeks'

示例2:
使用os.ftruncate()截断文件的方法

# Python program to explain os.ftruncate() 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 - 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.ftruncate() method 
os.ftruncate(fd, 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'


相关用法


注:本文由纯净天空筛选整理自Rajnis09大神的英文原创作品 Python | os.ftruncate() method。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。