简体   繁体   中英

Python-yaml script and double quotes

(Python 3.8) I am working on a script that reads a txt file and dumps data into a yaml file. It is working great but the only problem is the single quotes that appear in the output. I just need double quotations and not the single quotes around them.

info.txt

Adam
Ariel
Addison
Brianna
Brittany
Courtney

School.py

from pathlib import Path
import ruamel.yaml
#import pprint
b = '171/'
in_file = Path('info.txt')
out_file = Path('record.yml')
yaml = ruamel.yaml.YAML()
data = []
index = 0
f = open('record.yml', 'w')
f.close()
file_object= open('record.yml','a')
file_object.write(' Division=71\n Sector=Infrastructure\n')
#file_object.close()
for line in in_file.open():
 line = line.strip()
 index +=1
 data.append(dict(name =(f'"'+line+'"'), ID = "%s%s" % (f'"'+b+'',f''+line+'"')))

yaml.dump(data,file_object)

Output record.yml file:

 Division=71
 Sector=Infrastructure
- name: '"Adam"'
  ID: '"171/Adam"'
- name: '"Ariel"'
  ID: '"171/Ariel"'
- name: '"Addison"'
  ID: '"171/Addison"'
- name: '"Brianna"'
  ID: '"171/Brianna"'
- name: '"Brittany"'
  ID: '"171/Brittany"'
- name: '"Courtney"'
  ID: '"171/Courtney"'

Desired output:

 Division=71
 Sector=Infrastructure
- name: "Adam"
  ID: "171/Adam"
- name: "Ariel"
  ID: "171/Ariel"
- name: "Addison"
  ID: "171/Addison"
- name: "Brianna"
  ID: "171/Brianna"
- name: "Brittany"
  ID: "171/Brittany"
- name: "Courtney"
  ID: "171/Courtney"

If you add double quotes in your code, they will be added to the content. You don't want them to be part of the content, so don't add them.

There is no reason to force double quotes in your output. Its semantic is identical without the double quotes. However if you really want to have them, use a custom representer:

class DoubleQuoted(str):
  pass

def represent_double_quoted(dumper, data):
  return dumper.represent_scalar(BaseResolver.DEFAULT_SCALAR_TAG,
      data, style='"')

yaml.add_representer(DoubleQuoted, represent_double_quoted)

Now you can use this class for content you want to double-quote, eg

name=(DoubleQuoted(line))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM