Python 文件 truncate() 方法



Python 文件 **truncate()** 方法用于截断或缩短文件的大小。换句话说,此方法删除文件的内容,并用一些垃圾(或空)值替换它们以保持大小。此文件的大小默认为文件中的当前位置。

此方法接受一个可选的 size 参数,文件将被截断到(最多)该大小。此参数的默认值为当前文件位置。但是,如果 size 参数超过文件的当前大小,则通过向文件中添加未定义的内容或零来将文件增加到指定的大小。结果取决于平台。

**注意** - 如果文件以只读模式打开,则 truncate() 方法将不起作用。

语法

以下是 Python 文件 **truncate()** 方法的语法:

fileObject.truncate(size)

参数

  • **size** - (可选)要截断文件的大小。

返回值

此方法不返回值。

示例

考虑一个包含字符串的演示文件“foo.txt”。

This is 1st line
This is 2nd line
This is 3rd line
This is 4th line
This is 5th line

以下示例显示了 Python 文件 truncate() 方法的用法。

# Open a file
fo = open("foo.txt", "w+")
print("Name of the file: ", fo.name)

# Assuming file has following 5 lines
# This is 1st line
# This is 2nd line
# This is 3rd line
# This is 4th line
# This is 5th line

line = fo.readline()
print("Read Line:", line)

# Now truncate remaining file.
fo.truncate()

# Try to read file now
line = fo.readline()
print("Read Line:", line)

# Close opened file
fo.close()

运行上述程序时,会产生以下结果:

Name of the file:  foo.txt
Read Line:
Read Line:

示例

如果我们将 size 参数传递给该方法,则文件的内容将被截断,但文件的大小将等于传递的参数。

演示文件“foo.txt”的大小为 138 字节,size 参数设置为 50 字节,该方法将删除当前文件中的现有内容,并用未定义的内容填充文件。因此,文件的大小减小到 50 字节。

# Open a file
fo = open("foo.txt", "w+")
print("Name of the file: ", fo.name)

# Read the first line of the file
line = fo.readline()
print("Read Line:", line)

# Now truncate the file and maintain the size up to 50 bytes
fo.truncate(50)

# Try to read the file now
line = fo.readline()
print("Read Line:", line)

# Close opened file
fo.close()

运行上面的程序后,将显示如下输出,并检查文件大小以观察结果。

Name of the file:  foo.txt
Read Line:
Read Line:

示例

但是,如果给定的 size 参数超过文件大小,则通常会截断其中的内容,并且文件将用未定义的内容或零填充。

演示文件“foo.txt”的大小为 138 字节,如果 size 参数设置为 200 字节,则该方法将用未定义的内容填充文件,同时将文件大小保持在 200 字节。

# Open a file
fo = open("foo.txt", "w+")
print("Name of the file: ", fo.name)

# Read the first line of the file
line = fo.readline()
print("Read Line:", line)

# Now truncate the file and maintain the size up to 200 bytes
fo.truncate(200)

# Try to read the file now
line = fo.readline()
print("Read Line:", line)

# Close opened file
fo.close()

运行上面的程序后,将显示如下输出。要检查文件的大小,请转到此文件的属性。

Name of the file:  foo.txt
Read Line:
Read Line:

示例

当文件处于读取模式 (r 或 r+) 时,此方法不起作用。

在此示例中,文件以读取模式 (r+) 打开,在此文件的对象上调用的 truncate 方法将无效,并保持其内容与之前相同。

# Open a file
fo = open("foo.txt", "r+")
print("Name of the file: ", fo.name)

# Read the first line of the file
line = fo.readline()
print("Read Line:", line)

# Now truncate the file
fo.truncate()

# Try to read the file now
line = fo.readline()
print("Read Line:", line)

# Close opened file
fo.close()

运行上面的程序后,将显示如下输出:

Name of the file:  foo.txt
Read Line: This is 1st line

Read Line: This is 2nd line
python_file_methods.htm
广告