【问题标题】:How to write in text file by variable using python 2.7 [duplicate]如何使用python 2.7通过变量写入文本文件[重复]
【发布时间】:2018-06-30 18:54:54
【问题描述】:

我已将字符串存储在一个变量中。我想将它附加到一个文本文件中。我怎样才能做到这一点?

 def readyaml(abs_read_path,):
        with open(abs_read_path, 'r') as stream, open("instanceinput.txt",'w') as fnew: 
            try:
                content = yaml.load(stream)
                instance = content['instance']
                dump = instance[0]
                print dump
                fnew.write(dump)
            except yaml.YAMLError as exc:
                print(exc)
        stream.close()
        fnew.close()

    readyaml(abs_read_path)

【问题讨论】:

  • 您可能想阅读file operationPEP 434 上的文档。您会注意到,在使用上下文管理器时,您不必close 文件对象。实际错误显然是由于dump 不是字符串。你检查dump的类型了吗?

标签: python


【解决方案1】:

您需要使用 Vikas & Mayur 提到的 append 方法,并且在写入文件时将其转换为 sting 对象:

例子:

def readyaml(abs_read_path,):
        with open(abs_read_path, 'r') as stream, open("instanceinput.txt",'a') as fnew:
            try:
                content = yaml.load(stream)
                instance = content['instance']
                dump = instance[0]
                print dump
                fnew.write(str(dump))  # CONVERT TO STRING OBJECT
            except yaml.YAMLError as exc:
                print(exc)
        stream.close()
        fnew.close()

    readyaml(abs_read_path)

【讨论】:

  • 谢谢你..它为我工作..
【解决方案2】:

使用a 代替w

 with open(abs_read_path, 'r') as stream, open("instanceinput.txt",'a') as fnew:

【讨论】:

  • 我在 readyaml(abs_read_path) 文件“C: \Users*****\Desktop\ParseScript\readingYAML.py",第 25 行,在 readyaml fnew.write(dump) TypeError: 期望字符串或其他字符缓冲区对象
【解决方案3】:

您可以使用'a''a+' 代替'w'

'a' 如果文件不存在,则创建该文件。 打开以写入并附加数据。

'a+'文件不存在则创建。 为读取和写入打开并在写入时附加数据。

【讨论】:

    猜你喜欢
    • 2018-09-18
    • 1970-01-01
    • 2021-04-04
    • 1970-01-01
    • 1970-01-01
    • 2016-06-22
    • 2016-02-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多