python中truncate的用法_Python os.truncate()用法及代码示例

操作系统模块Python中的Windows提供了与操作系统进行交互的功能。操作系统属于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'

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值