【问题标题】:Changing part of file (txt) in Python? [closed]在 Python 中更改文件(txt)的一部分? [关闭]
【发布时间】:2014-04-05 18:00:32
【问题描述】:

我想知道是否可以使用 Python 更改 txt/yaml 文件中一行的一部分?

我有这样的文件:

main:
  Player1:
    points: 5
  Player2:
    points: 2

我想要更改指定玩家的积分(即 Player1 有 5 分,我想将其更改为 10)?这可能吗?

提前致谢!

【问题讨论】:

  • 到目前为止你尝试了什么?
  • @Selcuk tbh,什么都没有,因为我什至不知道从哪里开始,我正在看空白一小时哈哈。。
  • 您可以轻松地将特定字符更改为另一个(查看随机文件访问),但从 5 变为 10 需要插入一个字符。为此,您必须读取文件、进行更改并写出新文件。
  • 使用PyYAML (docs)

标签: python file yaml


【解决方案1】:

实现你想要的最聪明的方法是解析yaml文件,对解析的内容进行更改,然后重写文件。

这比以某种方式弄乱原始文件要强大得多。您拥有有效的指定表示 (yaml) 中的数据,使用它是有意义的。

你需要先安装 pyYAML,这样你就有了解析文件的代码。 (使用简单安装或 pip)。

下面的 sn-p 可以满足您的需要。我注释了每一行来告诉你它的作用。我鼓励您理解每一行,而不仅仅是复制粘贴这个示例,因为这就是您学习编程语言的方式。

# 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)

【讨论】:

  • +1 不错的第一个答案。继续前进。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-19
  • 2020-03-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多