使用正确的多行转储yaml文件而不使用Python的换行符

时间:2018-02-12 15:50:43

标签: python yaml

我需要在yaml中重新创建该文件:

- account_type: 3
  active: true
  addresses: 
  - address: !!python/unicode 'firstname.lastname@email.com'
    enabled: true
    username: !!python/unicode 'firstname.lastname@email.com'
  email: !!python/unicode 'firstname.lastname@email.com'
  firstname: firstname
  high_score: 0.0
  lastname: lastname
  lists: []
  local: false
  low_score: 0.0
  password1: !!python/unicode 'Deef2fht'
  password2: !!python/unicode 'Deef2fht'
  send_report: true
  signatures: []
  spam_checks: true
  timezone: !!python/unicode 'Europe/Rome'
  username: !!python/unicode 'firstname.lastname@email.com'

所以我创建了这段代码:

import yaml
import random
import string
import sys
email = sys.argv[1]
dominio = email.split("@")
nome = (dominio[0].split("."))[0]
cognome = (dominio[0].split("."))[1]
password = random = ''.join([random.choice(string.ascii_letters + string.digits) for n in xrange(8)])
document = """
  account_type: 3
  active: true
  addresses: 
    address: '"""+email+"""'
    enabled: true
    username: '"""+email+"""'
    email: '"""+email+"""'
  firstname: """+nome+"""
  high_score: 0.0
  lastname: """+cognome+"""
  lists: []
  local: false
  low_score: 0.0
  password1: '"""+password+"""'
  password2: '"""+password+"""'
  send_report: true
  signatures: []
  spam_checks: true
  timezone: 'Europe/Rome'
  username: '"""+email+"""'
"""
yaml.safe_dump(document, open("output.yaml", "w"), default_flow_style=False)

但是输出只在一行上,并且对于我的文档变量i' ve / n字符的每个换行符。 有一种方法可以在不打印不同变量的每一行的情况下做到这一点吗?

1 个答案:

答案 0 :(得分:2)

不是使用字符串连接,而是构建一个表示yml对象的字典。然后使用yaml.dump()将其写回磁盘。理解yaml库如何工作的一种简单方法是将现有文件加载到变量中,更改一些值并将其写回磁盘。

  1. 使用您的目标yaml创建一个foo.yml文件:

    - account_type: 3
      active: true
      addresses: 
      - address: !!python/unicode 'firstname.lastname@email.com'
        enabled: true
        username: !!python/unicode 'firstname.lastname@email.com'
      email: !!python/unicode 'firstname.lastname@email.com'
      firstname: firstname
      high_score: 0.0
      lastname: lastname
      lists: []
      local: false
      low_score: 0.0
      password1: !!python/unicode 'Deef2fht'
      password2: !!python/unicode 'Deef2fht'
      send_report: true
      signatures: []
      spam_checks: true
      timezone: !!python/unicode 'Europe/Rome'
      username: !!python/unicode 'firstname.lastname@email.com'
    
  2. 将文件读入变量,浏览它的结构,更改用户名并将新的yml文件保存回磁盘。

    import yaml
    x = {}
    with open('foo.yml', 'r') as my_file:
        x = yaml.load(my_file)
    
    x[0]['username'] = 'different_user@domain.com'
    
    with open('new.yml', 'w') as new_file:
        yaml.dump(x, new_file)