📜  Python| os.truncate() 方法

📅  最后修改于: 2022-05-13 01:55:21.318000             🧑  作者: Mango

Python| os.truncate() 方法

Python中的OS 模块提供了与操作系统交互的功能。操作系统属于 Python 的标准实用程序模块。该模块提供了一种使用操作系统相关功能的可移植方式。

Python中的os.truncate()方法用于将指定路径所指示的文件截断到最多指定长度。

将以下文本视为名为Python_intro.txt的文件的内容。

代码 #1:使用 os.truncate() 方法
# Python program to explain os.truncate() method 
    
# importing os module 
import os
  
# File path
path = "/home / ihritik / Desktop / Python_intro.txt"
  
# Print the original size of the file (in bytes)
print("File size (in bytes):", os.path.getsize(path))
  
# Length (in Bytes) to which 
# the file will be truncated
length = 72
  
# Truncate the file 
# to at most given length
# using os.truncate() method
os.truncate(path, length)
  
# Print the content of file
print("Content of file Python_intro.txt:")
with open(path, 'r') as f:
    print(f.read()) 
  
# Print the new size of the file (in bytes)
print("File size (in bytes):", os.path.getsize(path))
输出:
File size (in bytes): 409
Content of file Python_intro.txt:
Python is a widely used general-purpose, high level programming language
File size (in bytes): 72

将以下文本视为名为Python_intro.txt的文件的新内容。

代码#2:如果指定长度超过文件大小
# Python program to explain os.truncate() method 
    
# importing os module 
import os
  
# File path
path = "/home / ihritik / Desktop / Python_intro.txt"
  
# Print the original size of the file (in bytes)
print("File size (in bytes):", os.path.getsize(path))
  
# Length (in Bytes) to which 
# the file will be truncated
length = 72
  
# Truncate the file 
# to at most given length
# using os.truncate() method
os.truncate(path, length)
  
# Print the content of file
print("Content of file Python_intro.txt:")
with open(path, 'r') as f:
    print(f.read()) 
  
# Print the new size of the file (in bytes)
print("File size (in bytes):", os.path.getsize(path))
输出:
File size (in bytes): 72
Content of file Python_intro.txt:
Python is a widely used general-purpose, high level programming language

File size (in bytes): 100

将大小为 72 字节的文件截断为 100 字节后的实际文件内容:
Python_intro.txt
文件内容达到其原始大小并没有改变,而是将文件大小增加到指定的大小,它被一些无效字符填充。

代码 #3:使用 os.truncate() 方法删除文件内容
# Python program to explain os.truncate() method 
    
# importing os module 
import os
  
# File path
path = "/home / ihritik / Desktop / Python_intro.txt"
  
# Print the original size of the file (in bytes)
print("File size (in bytes):", os.path.getsize(path))
  
# specify the length as 0
# to delete the file content
length = 0
  
# Truncate the file 
# to length 0
os.truncate(path, length)
  
# Print the content of file
print("Content of file Python_intro.txt:")
with open(path, 'r') as f:
    print(f.read()) 
  
# Print the new size of the file (in bytes)
print("File size (in bytes):", os.path.getsize(path))
  
# Consider the same Python_intro.txt file
# used in above example for this example
输出:
File size (in bytes): 100
Content of file Python_intro.txt:

File size (in bytes): 0