【问题标题】:appending text to a file. %s f.name将文本附加到文件。 %s f.name
【发布时间】:2014-05-04 12:03:35
【问题描述】:
import os

def closed(x):
        if f.closed == True:
                return "closed"
        else:
                return "open"

f = open("test.txt", "ab")
print "Name of the file: ", f.name
print "we just opened the file so the file is: ", closed(f)
f.write("I am writing now to the file %s \n") % (f.name)
f.close()
print "now we typed f.close(), so it is: ", closed(f)

它给了我错误,并打印到 test.txt %s 并且不理解 %s?为什么?

Traceback(最近一次调用最后一次): 文件“attempt1.py”,第 12 行,在 f.write("我现在正在写入文件 %s \n") % (f.name) TypeError: 不支持的操作数类型 %: 'NoneType' 和 'str'

我希望它使用 %s 写入“我现在正在写入文件 test.txt”

【问题讨论】:

    标签: python text filenames


    【解决方案1】:

    你没有正确格式化字符串,修复这一行:

    f.write("I am writing now to the file %s \n" % f.name)
    

    在您的代码中,由于% (f.name) 不是有效的Python,您关闭了括号,使字符串未格式化并出现SyntaxError。

    顺便说一句,str.format() 改进了这种格式。像这样的:

    f.write("I am writing now to the file {} \n".format(f.name))
    

    【讨论】:

      【解决方案2】:

      您的 % 超出打印尝试范围

      f.write("I am writing now to the file %s \n" % f.name)
      

      【讨论】:

        【解决方案3】:

        为了扩展 Paulo Bu 的答案,文件处理也得到了改进。 我说的是Context Managers。 他们会自动为您在托管对象上调用.close()。

        这是你的 sn-p 的样子:

        import os
        
        with open("test.txt", "a") as f:
            print("Name of the file:", f.name)
            f.write("I am writing now to the file {} \n".format(f.name))
        

        此外,您会注意到我从open() 的mode 参数中删除了"b"。 看起来您只是在附加文本,而不是二进制数据,因此 "b" 没有意义。 看看这里 (python's built-in open function docs) 可以传递给 mode 的标志以及它们的含义。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2018-05-05
          • 1970-01-01
          • 2021-12-13
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多