【问题标题】:AttributeError "truncate"属性错误“截断”
【发布时间】:2023-04-03 17:30:01
【问题描述】:

我是 Python 新手,我正在尝试弄清楚一些事情。我正在运行以下代码,其中创建了两个函数来打开和擦除文件。

from sys import argv

script, filename = argv

def erase(text):
    print open(text, "w")
    text.truncate()

piece = filename

print "here I am erasing it"
print erase(piece)

文件实际上被删除了,但我得到一个错误:

AttributeError: "str" object has no attribute to "truncate".

我正在导入的文件存在并且其中包含字符串。有什么问题?

【问题讨论】:

    标签: python truncate attributeerror


    【解决方案1】:
    def erase(text):
        print open(text, "w")
        text.truncate()
    

    在那个函数中text 是文件名,一个字符串。因此,在打印出open() 返回的文件对象后,您可以在文件名而不是文件对象上调用truncate()

    您必须将open() 的返回值存储在一个变量中,然后在该对象上调用truncate()

    或者更好的是,使用with 声明:

    def erase(filename):
        with open(filename, "w") as f:
            f.truncate()
    

    正如 Rob 在 cmets 中指出的那样,打开模式 w 已经截断了文件,因此打开它之后,您实际上不需要做任何事情:

    def erase(filename):
        with open(filename, "w") as f:
            pass
    

    【讨论】:

    • 无需截断任何内容。当你使用 open(..., 'w') 时,它已经截断了文件。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-22
    • 2016-08-06
    • 2013-01-15
    • 1970-01-01
    相关资源
    最近更新 更多