Python File truncate() 方法



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

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

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

语法

以下是 Python File 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 File 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