- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有代码应该抓取 YAML 文件并将其读入(成功),但也应该能够更新 YAML 返回三个选项之一:
第二个和第三个选项效果很好,但每当我更新时,第一个选项都会返回 TypeError:字符串索引必须是整数
或 TypeError:'int' object is not iterable
我的字典 d 中嵌套字典之外的任何值。
这是我想出的代码:
class YAML_Config:
'''
Class used to interact with .YAML filetypes. Allows the creation of objects \
that can be manipulated and save certain YAML files and configuration settings.
'''
def __init__(self, filename):
'''
Initial defintion. Defines the location for saving a new .YAML file or for loading \
a previous one. The dictionary corresponding to the .YAML file is saved to self.dict. \
If this is a new .YAML file, an empty dictionary is created.
Input Arguments:
-filename: (string) The name of the file where the current .YAML file is \
located or the new .YAML will be saved.
'''
#Get the filename and save it to the class as a property.
self.file = filename
#Check if the file exists...
if os.path.isfile(self.file):
#Prepare to open the file with reading capabilities
with open(self.file,'r') as infile:
#Get a dictionary with all of the YAML informatin.
yaml_dict = yaml.load(infile)
#If the file does not exist...
else:
#Create an empty dictionary to save all YAML data.
yaml_dict = {}
#Create an empty .yaml file with the dictionary.
with open(self.file, 'w') as infile:
#Save updated dictionary to YAML file.
yaml.dump(yaml_dict, infile, default_flow_style=False)
print('YAML configuration file not found. New, empty dictionary, and .yaml file created.')
self.dict=yaml_dict
def update_value(self, kwargs):
'''
Used to update YAML files, and checks that the files were updated properly.
'''
#If these are not keyword arguments, then throw an error.
assert kwargs, 'Input Error'
#Get the YAML dictionary before it is updated.
yaml_dict = self.dict
#Make a copy of the dictionary to compare against later.
yaml_dict_original = copy.deepcopy(self.dict)
#Check if the dictionary is nonetype. This happens if the file is new as the file is empty.
if yaml_dict_original is None:
#Redefine orginal dictionary as an empty dictionary.
yaml_dict_original={}
#The new dictionary will simply be what is passed to the function.
yaml_dict=kwargs
else:
#Update the original dictionary and update it with the arguments passed.
#This also updates self.dict as yaml_dict is simply a reference to
#that dictionary, not a copy of it.
yaml_dict.update(kwargs)
#Check if changes were made
if (yaml_dict==yaml_dict_original) is False:
#Open the YAML file to write to it.
with open(self.file, 'w') as outfile:
#Save updated dictionary to YAML file.
yaml.dump(self.dict, outfile, default_flow_style=False)
#Check that the file actually updated properly:
#Double-check the file that it actually updated.
with open(self.file, 'r') as infile:
lastupdate = yaml.load(infile)
#Get any nonmatching values between what should be in the YAML file and what actually is.
errors = { k : yaml_dict[k] for k in set(yaml_dict) - set(lastupdate) }
#Find out what changed in the YAML file.
edits = { k : yaml_dict_original[k] for k in set(yaml_dict_original) - set(lastupdate) }
#Check if errors is not empty. Evaluating dictionaries as boolean either returns True (not empty)
#or False (empty).
if bool(errors) is True:
#First line of return print statement.
print('The following entries did not update successfully:')
#Loop through keys in errors
for n in errors:
#Print the current key
print (n)
#Loop through entries of current key
for m in errors[n]:
#Print current entry of current key
print (m,':',errors[n][m])
#Saved properly, check for edits and display to user.
else:
#Find where any edits were made.
edits = {k: yaml_dict_original[k] for k in yaml_dict_original if k in lastupdate and yaml_dict_original[k] != lastupdate[k]}
#Show user what edits were successfuly made.
print('%s was successfully updated with the following changes:' % os.path.basename(self.file))
#Loop through keys in edits
for n in edits:
#Print the current key
print (n)
#Loop through entries of current key
for m in edits[n]:
#Print current entry of current key
print (m,':',edits[n][m])
#If no changes were made...
else:
#Show user what edits were successfuly made.
print('No changes to %s were passed. File not updated.' %
os.path.basename(self.file))
test=YAML_Config(r'...Path\Python Work\yaml_test.yaml')
d = {'A': 7, 'B':{'C':'D', 'D':False, 'E':'Julio'},\
'The Real C': {'J?':'Yes, this is J.', 'K' : 241},'Q' : 'PQ'}
test.update_value(d)
第一个错误部分:
b = {'A': '', 'B':{'C':'D', 'D':False, 'E':'Julio'},\
'The Real C': {'J?':'Yes, this is J.', 'K' : 241},'Q' : 'PQ'}
#TypeError: string indices must be integers.
test.update_value(b)
第二个错误部分:
f = {'A': 7, 'B':{'C':'D', 'D':False, 'E':'Julio'},\
'The Real C': {'J?':'Yes, this is J.', 'K' : 241},'Q' : 2}
#TypeError: 'int' object is not iterable.
test.update_value(f)
每次运行此代码时,YAML 文件都会更新。所以实际的更新正在工作,但我不太确定为什么我找不到字典更新的索引。我对 Python 有点生疏,而且对 YAML 还很陌生,所以我可能会在这里遗漏一些明显的东西。
我使用的是 Python 3.6.5。
最佳答案
您的代码在这一行出错:
# Loop through entries of current key
for m in edits[n]:
此时 edits
是一个字典:{A: 7}
(因为 A 是具有更改值的键)。您的代码似乎只预测复杂值的变化(例如 B
的变化),因为如果您这样做:
b = {'A': 7, 'B':{'C':'D', 'D':True, 'E':'Julio'},\
'The Real C': {'J?':'Yes, this is J.', 'K' : 241},'Q' : 'PQ'}
你得到:
test.yaml was successfully updated with the following changes:
B
C : D
D : False
E : Julio
因此,您应该重新考虑您的“报告”并将其更新为不仅可以处理 dict
值,还可以处理 list
和基元(YAML 标量)的值:字符串、整数、 bool 值等):
# Show user what edits were successfuly made.
print('{} was successfully updated with the following changes:'.format(os.path.basename(self.file)))
# Loop through keys in edits
for n in edits:
# Loop through entries of current key
if isinstance(edits[n], dict):
# Print the current key
print(n)
for m in edits[n]:
# Print current entry of current key
print(m, ':', edits[n][m])
elif isinstance(edits[n], list):
# Print the current key followed by the elements
print(n)
for m in edits[n]:
# Print current entry of current key
print('- ', [m])
else: # scalar
print('{}: {}'.format(n, edits[n]))
然后你的输出将是:
test.yaml was successfully updated with the following changes:
A: 7
test.yaml was successfully updated with the following changes:
A:
Q: PQ
(假设您相继运行两个额外更新)。
关于python - 不返回 YAML 文件的更新并在字符串更新时返回 TypeError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51153553/
SQLite、Content provider 和 Shared Preference 之间的所有已知区别。 但我想知道什么时候需要根据情况使用 SQLite 或 Content Provider 或
警告:我正在使用一个我无法完全控制的后端,所以我正在努力解决 Backbone 中的一些注意事项,这些注意事项可能在其他地方更好地解决......不幸的是,我别无选择,只能在这里处理它们! 所以,我的
我一整天都在挣扎。我的预输入搜索表达式与远程 json 数据完美配合。但是当我尝试使用相同的 json 数据作为预取数据时,建议为空。点击第一个标志后,我收到预定义消息“无法找到任何内容...”,结果
我正在制作一个模拟 NHL 选秀彩票的程序,其中屏幕右侧应该有一个 JTextField,并且在左侧绘制弹跳的选秀球。我创建了一个名为 Ball 的类,它实现了 Runnable,并在我的主 Draf
这个问题已经有答案了: How can I calculate a time span in Java and format the output? (18 个回答) 已关闭 9 年前。 这是我的代码
我有一个 ASP.NET Web API 应用程序在我的本地 IIS 实例上运行。 Web 应用程序配置有 CORS。我调用的 Web API 方法类似于: [POST("/API/{foo}/{ba
我将用户输入的时间和日期作为: DatePicker dp = (DatePicker) findViewById(R.id.datePicker); TimePicker tp = (TimePic
放宽“邻居”的标准是否足够,或者是否有其他标准行动可以采取? 最佳答案 如果所有相邻解决方案都是 Tabu,则听起来您的 Tabu 列表的大小太长或您的释放策略太严格。一个好的 Tabu 列表长度是
我正在阅读来自 cppreference 的代码示例: #include #include #include #include template void print_queue(T& q)
我快疯了,我试图理解工具提示的行为,但没有成功。 1. 第一个问题是当我尝试通过插件(按钮 1)在点击事件中使用它时 -> 如果您转到 Fiddle,您会在“内容”内看到该函数' 每次点击都会调用该属
我在功能组件中有以下代码: const [ folder, setFolder ] = useState([]); const folderData = useContext(FolderContex
我在使用预签名网址和 AFNetworking 3.0 从 S3 获取图像时遇到问题。我可以使用 NSMutableURLRequest 和 NSURLSession 获取图像,但是当我使用 AFHT
我正在使用 Oracle ojdbc 12 和 Java 8 处理 Oracle UCP 管理器的问题。当 UCP 池启动失败时,我希望关闭它创建的连接。 当池初始化期间遇到 ORA-02391:超过
关闭。此题需要details or clarity 。目前不接受答案。 想要改进这个问题吗?通过 editing this post 添加详细信息并澄清问题. 已关闭 9 年前。 Improve
引用这个plunker: https://plnkr.co/edit/GWsbdDWVvBYNMqyxzlLY?p=preview 我在 styles.css 文件和 src/app.ts 文件中指定
为什么我的条形这么细?我尝试将宽度设置为 1,它们变得非常厚。我不知道还能尝试什么。默认厚度为 0.8,这是应该的样子吗? import matplotlib.pyplot as plt import
当我编写时,查询按预期执行: SELECT id, day2.count - day1.count AS diff FROM day1 NATURAL JOIN day2; 但我真正想要的是右连接。当
我有以下时间数据: 0 08/01/16 13:07:46,335437 1 18/02/16 08:40:40,565575 2 14/01/16 22:2
一些背景知识 -我的 NodeJS 服务器在端口 3001 上运行,我的 React 应用程序在端口 3000 上运行。我在 React 应用程序 package.json 中设置了一个代理来代理对端
我面临着一个愚蠢的问题。我试图在我的 Angular 应用程序中延迟加载我的图像,我已经尝试过这个2: 但是他们都设置了 src attr 而不是 data-src,我在这里遗漏了什么吗?保留 d
我是一名优秀的程序员,十分优秀!