简体   繁体   English

Python - 从 yml 文件中获取空密钥

[英]Python - Get empty key from yml file

I have a lot yaml file names that have similar structure but with different data.我有很多结构相似但数据不同的 yaml 文件名。 I need to parse out selective data, and put into a single csv (excel) file as three columns.我需要解析出选择性数据,并将其作为三列放入单个 csv (excel) 文件中。

But i facing an issue with empty key, that always gives me an "KeyError: 'port'"但我面临一个空键问题,总是给我一个“KeyError:'port'”

my yaml file example:我的 yaml 文件示例:

base:
   server: 10.100.80.47
   port: 3306
   namePrefix: well
   user: user1
   password: kjj&%$

 base:
   server: 10.100.80.48
   port: 
   namePrefix: done
   user: user2
   password: fhfh#$%

In the second block i have an empty "port", and my script is stuck on that point.在第二个块中,我有一个空的“端口”,而我的脚本就卡在了这一点上。 I need that always that an empty key is found it doesn't write anything.我总是需要找到一个空键,它不会写任何东西。

   from asyncio.windows_events import NULL
   from queue import Empty
   import yaml
   import csv
   import glob


   yaml_file_names = glob.glob('./*.yaml')

   rows_to_write = []

   for i, each_yaml_file in enumerate(yaml_file_names):
   print("Processing file {} of {} file name: {}".format(
    i+1, len(yaml_file_names),each_yaml_file))

   with open(each_yaml_file) as file: 
    data = yaml.safe_load(file)


   for v in data:
    if "port" in v == "": 
    data['base']['port'] = ""  



  rows_to_write.append([data['base']['server'],data['base']['port'],data['server']['host'],data['server']['contex']])


  with open('output_csv_file.csv', 'w', newline='') as out:
    csv_writer = csv.writer(out)
    csv_writer.writerow(["server","port","hostname", "contextPath"])
    csv_writer.writerows(rows_to_write)
    print("Output file output_csv_file.csv created")

输出

You are trying to access the key by index eg您正在尝试按索引访问密钥,例如

data['base']['port']

But what you want is to access it with the get method like so:但是您想要的是使用 get 方法访问它,如下所示:

data['base'].get('port')

This way if the key does not exists it return None as default, and you could even change the default value to whatever you want by passing it as the second parameter.这样,如果键不存在,它将默认返回 None,您甚至可以通过将其作为第二个参数传递来将默认值更改为您想要的任何值。

In PyYAML, an empty element is returned as None , not an empty string.在 PyYAML 中,空元素返回为None ,而不是空字符串。

if data['base']['port'] is None: 
    data['base']['port'] = "" 

Your yaml file is invalid.您的 yaml 文件无效。 In yaml file, whenever you have a key (like port: in your example) you must provide a value, you cannot leave it empty and go to the next line.在 yaml 文件中,只要您有一个密钥(如您的示例中的port: :),您就必须提供一个值,您不能将其留空,并将 go 留到下一行。

This is likely why you cannot parse the file as expected with the python yaml module.这可能是您无法使用 python yaml 模块按预期解析文件的原因。 If you are the creator of those yaml file, you really need to put a key in the file like port: None if you don't want to provide a value for the port, or even better you just not provide any port key at all.如果您是那些 yaml 文件的创建者,您真的需要在文件中放置一个密钥,例如port: None如果您不想为端口提供值,或者更好的是您根本不提供任何端口密钥.

Then the other solutions should work.然后其他解决方案应该可以工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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