如何使用python 2.7通过变量在文本文件中写入

时间:2018-01-22 07:31:49

标签: python

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

 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)

3 个答案:

答案 0 :(得分:2)

使用a代替w

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

答案 1 :(得分:2)

您需要使用追加方法 Vikas& Mayur提到了,并且当写入文件时将其转换为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 :(得分:1)

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

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

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