【问题标题】:Python truncate function isnt working as expectedPython truncate 函数未按预期工作
【发布时间】:2020-01-17 06:02:12
【问题描述】:

我对 python 中的 truncate 函数有点困惑。 truncate 函数不应该清空文件并仅显示第二行输入吗?但在我的文件中,第一行和第二行输入都在程序结束后的文件中。

文件中的预期输出

Line2 input

文件中的当前输出

Line1 input Line2 input

如果我使用 .truncate(0),这就是我在文件中得到的内容

from sys import argv

script, filename = argv

print(f"Erasing the file {filename}")

print("Opening the file...")
# This empties and overrides the file when opening in w mode use 'a' to append to file
target = open(filename, 'w')

line = input("Input a line")

target.write(line)

print("Truncating ie erasing the file...")
target.truncate()

line2 = input("Input another line")

target.write(line2)

target.close()

请帮忙

【问题讨论】:

  • 可能重复。在这里查看答案:stackoverflow.com/a/26917275/7977464
  • 试试truncate(0)
  • truncate() 删除了当前光标位置之后(第一行之后)的文件内容。它实际上什么都不做,因为光标在文件的末尾。
  • 试过你们说的。请检查问题的编辑部分

标签: python python-3.x truncate


【解决方案1】:

the docs,强调我的:

将流的大小调整为以字节为单位的给定大小(如果未指定大小,则为当前位置)。当前流的位置没有改变。

您需要调用 .truncate(0) 将文件截断为零字节。

【讨论】:

  • 试过你说的。请检查问题的编辑部分。
  • 如果您想将文件倒回到开头,您还需要.seek(0)
猜你喜欢
  • 2022-12-19
  • 1970-01-01
  • 1970-01-01
  • 2018-02-01
  • 2019-10-30
  • 2015-04-11
  • 2022-01-25
  • 2019-12-22
  • 1970-01-01
相关资源
最近更新 更多