我想知道是否可以使用Python更改txt / yaml文件中一行的一部分?
我的文件是这样的:
main:
Player1:
points: 5
Player2:
points: 2
我想要的是改变指定玩家的积分(即Player1有5分,我想将其改为10分)?这可能吗?
提前致谢!
答案 0 :(得分:2)
实现所需目标的最明智的方法是解析yaml文件,对已解析的内容进行更改,然后重写文件。
这比以某种方式搞乱原始文件要强大得多。您拥有有效的指定表示(yaml)中的数据,并且使用它是有意义的。
首先需要安装pyYAML,因此您需要使用代码来解析文件。 (使用简单安装或点子)。
以下代码段可满足您的需求。我注释了每一行,告诉你它的作用。我鼓励你理解每一行,而不仅仅是复制粘贴这个例子,因为这就是你学习编程语言的方法。
# the library you need to parse the yaml file
import yaml
# maybe you are on Python3, maybe not, so this makes the print function work
# further down
from __future__ import print_function
#this reads the file and closes it once the with statement is over
with open('source.yml', 'r') as file_stream:
# this parses the file into a dict, so yml_content is then a dict
# you can freely change
yml_content = yaml.load(file_stream)
# proof that yml_content now contains your data as a dict
print(yml_content)
# make the change
yml_content['main']['Player1']['points'] = 10
#proof that yml_content now contains changed data
print(yml_content)
# transform the dict back to a string (default_flow_style makes the
# representation of the yml equal to the original file)
yml_string = yaml.dump(yml_content, default_flow_style=False)
# open a the file in write mode, transform the dict to a valid yml string
# write the string to the file, close the file
with open('source.yml', 'w') as new_file:
new_file.write(yml_string)