-2

I have stored the string in a variable. And I want to append it to a text file. How can I achieve this?

 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)
  • You may want to read the docs on [file operation](https://docs.python.org/2/tutorial/inputoutput.html#reading-and-writing-files), as well as [PEP 434](https://www.python.org/dev/peps/pep-0343/). You will notice that you do not have to `close` a file obeject when using a context manager. The actual error is obviously due to `dump` not beeing a string. Did you check the type of `dump`? – MaxPowers Jan 22 '18 at 08:02

3 Answers3

2

use a instead of w :

 with open(abs_read_path, 'r') as stream, open("instanceinput.txt",'a') as fnew:
Vikas Periyadath
  • 3,088
  • 1
  • 21
  • 33
  • I am getting the same error File "C:\Users\*****\Desktop\ParseScript\readingYAML.py", line 31, in readyaml(abs_read_path) File "C:\Users\*****\Desktop\ParseScript\readingYAML.py", line 25, in readyaml fnew.write(dump) TypeError: expected a string or other character buffer object –  Jan 22 '18 at 07:37
2

You need use the append method as Vikas & Mayur has mentioned and also when writing to a file convert it to a sting object:

Example:

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)
Rakesh
  • 81,458
  • 17
  • 76
  • 113
1

You can use 'a' or 'a+' instead of 'w'

'a' The file is created if it does not exist. Open for writing and appends the data.

'a+'The file is created if it does not exist. Open for both reading and writing and appends the data while writing.