Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing yaml file: attribute error

I'm trying to read a yaml file, replacing part of it and write the result it into the same file, but I get an attribute error.

Code

import yaml
import glob
import re
from yaml import load, dump
from yaml import CLoader as Loader, CDumper as Dumper
import io

list_paths = glob.glob("my_path/*.yaml")

for path in list_paths:    
    with open(path, 'r') as stream:
        try:
            text = load(stream, Loader=Loader)
            text = str(text)
            print text
            if "my_string" in text:
                start = "'my_string': '"
                end = "'"
                m = re.compile(r'%s.*?%s' % (start,end),re.S)
                m = m.search(text).group(0)
                text[m] = "'my_string': 'this is my string'"  
        except yaml.YAMLError as exc:
            print(exc)
    with io.open(path, 'w', encoding = 'utf8') as outfile:
        yaml.dump(text, path, default_flow_style=False, allow_unicode=True)

Error I get this error for the yaml_dump line

AttributeError: 'str' object has no attribute 'write' 

What I have tried so far

  • Not converting the text to a string, but then I get an error on the m.search line:

    TypeError: expected string or buffer

  • Convert first to string and then to dictagain, but I get this error from the code text: dict(text) : ValueError: dictionary update sequence element #0 has length 1; 2 is required

Yaml file

my string: something
string2: something else

Expected result: yaml file

my string: this is my string
string2: something else
like image 953
Barbara Avatar asked Feb 14 '26 12:02

Barbara


2 Answers

To stop getting that error all you need to do is change the

with io.open(path, 'w', encoding = 'utf8') as outfile:
    yaml.dump(text, path, default_flow_style=False, allow_unicode=True)

to

with open(path, 'w') as outfile:
    yaml.dump(text.encode("UTF-8"), outfile, default_flow_style=False, allow_unicode=True)

As the other answer says, this solution simply replaces the string path with the open file descriptor.

like image 99
Kellie Lutze Avatar answered Feb 17 '26 01:02

Kellie Lutze


This

yaml.dump(text, path, default_flow_style=False, allow_unicode=True)

is not possible if path is a str. It must be an open file.