Get the App
SLTechnology News&Howtos  ›  Development  › 

How to read and write yaml files by Python

Shulou Source: shulou.com Published: 2022-06-01 04:42:50 09月18日 Update

This article mainly introduces Python how to read and write yaml files, the article is very detailed, has a certain reference value, interested friends must read it!

1. About yaml

Basic syntax rules of yaml:

Case sensitive

Use indentation to represent hierarchical relationships

The Tab key is not allowed when indenting, only spaces are allowed.

The number of indented spaces does not matter, as long as the elements at the same level are aligned to the left

# indicates a comment, which is ignored by the parser from this character to the end of the line, just like the comment in python

2.yaml data structure

There are three types of data structures supported by YAML:

Object

A collection of key-value pairs, also known as mapping / hashes / dictionary (dictionary)

A set of key-value pairs of objects, represented by a colon structure.

Array

A group of values arranged in order, also known as sequence / list

A set of lines at the beginning of a hyphenation line to form an array.

Scalar (scalars)

A single, irreparable value

Includes string, Boolean, integer, floating point, Null, time, date

3.yaml file format auth.login: data: name: '18888888883' password: jnyj123456 url: https://XXXX-api-XXXX.zje.com/auth/loginheaders: Accept:' * / * 'Accept-Encoding: gzip, deflate, br Accept-Language: zh-CN,zh Qroom0.9 Connection: keep-alive Content-Length: '46' Content-type: application/json Host: dexin-api-test.zje.com Origin: https://XXXX-spa-XXX.zje.com Referer: https://XXXX-spa-XXX.zje.com/ Sec-Fetch-Dest: empty Sec-Fetch-Mode: cors Sec-Fetch-Site: same-site User-Agent: Mozilla/5.0 (Macintosh Intel Mac OS X 10: 14: 6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.80 Safari/537.36 authorization: Bearer sec-ch-ua:'"Not Aten Brand"; v = "33" sec-ch-ua-mobile:? 0000 sec-ch-ua-platform: macOSis

Learning output:

Class OpenYaml (object): def _ _ init__ (self): self.file_path = os.path.join (route ("/ DataYaml/yaml.yaml")) # splice read file path def open (self) * args):''args [0]: dictionary name args [1]: field value read file' 'try: if len (args) = = 2: # execute content with open (self.file_path) based on passing value "r") as f: # read yaml Json = f.read () # get yaml Dict = yaml.safe_load (Json) [args [0]] # extract formulation if args [1] in Dict.keys (): # determine whether logs.info exists in key (f "yaml file) Content found successfully, content: {Dict [args [1]} ") return Dict [args [1]] else: print (f" corresponding field {args [1]} does not exist. ") Logs.info (f "corresponding field {args [1]} does not exist...") Else: with open (self.file_path, "r") as f: Json = f.read () Dict = yaml.safe_load (Json) [args [0]] return Dict except Exception as e: print (f' reads yaml file, error: {e}') logs.info (f' reads yaml file Error: {e}') def Wri_file (self, * args):'': param args: args [0] interface field, args [1] key, args [2] value: return: None write the field to yaml 'try: with open (self.file_path) Encoding= "utf-8") as f: # read the file data = yaml.load (f.read () Loader=yaml.FullLoader) # get read content print (data [args [0]]) if data is not None: # determine whether the read content is empty if str (data [args [0]] [args [1]]) in str (data [args [0]]): # determine whether name exists in dict data [args [0]] [ Args [1]] = args [2] with open (self.file_path 'wicked, encoding= "utf-8") as f: # write yaml.dump (data, stream=f, allow_unicode=True) else: print ("the field written to the file does not exist! Write failed. ") Else: logs.info ("the return value for writing to the file is empty! cannot write...") Except Exception as y: logs.info (f "failed to write to the file: {y}") if _ _ name__ = = "_ _ main__": OpenYaml (). Wri_file ("headers", "Content-Length", "22") OpenYaml (). Open ("auth.login", "data") these are all the contents of the article "how Python reads and writes yaml files". Thank you for reading! Hope to share the content to help you, more related knowledge, welcome to follow the industry information channel!

Tags: File content field structure dictionary character object hierarchy data data structure array comment space article utf-8 same important success value element Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Huawei Shulou Tech Info OPPO Reno NVidia Shulou Technology