【问题标题】:Replacing text certain line with some other text (python) closed [closed]用其他一些文本(python)替换文本某行已关闭[关闭]
【发布时间】:2017-12-08 16:51:36
【问题描述】:

我从其他论坛尝试了很多其他方法。但它们似乎都不起作用。也许我只是写错了。我有一个文本文件,我希望 python 用“1”替换“0”我的文本文件看起来像这样

0
hello
more stuff
meh

我希望它是

1
hello
more stuff
meh

谢谢,这可能真的很简单。 如果有人可以发布一种将 0 替换为 1 或删除整行然后重写它的方法。任何一个都有效。 谢谢 如果 0 在第三行或其他行上,我也希望它能够工作。你当然必须改变它的目标线

【问题讨论】:

  • 您想用1 替换每个0 吗?如果你有号码10,你希望它变成11吗?
  • 我希望它只替换某行上的“0”以使其变为“1”(只是自身的 0)
  • SO 不是您的编码服务,请编辑您的问题并向我们展示您迄今为止所做的尝试。如果您还没有,请拨打tour
  • 那么读取文本文件和解析值的代码在哪里?当然,您有一些起点并被困在某个地方,而不是在这里转向我们为读/写文本文件编写另一个答案以加入数千个现有答案?

标签: python python-3.x replace


【解决方案1】:

假设你想替换文件第一行的0

def replace_first_line(path, value, condition=None):
    with open(path, 'r') as file:
        lines = file.read().split('\n')
    if lines:
        first_line = lines[0]
        if not condition or first_line.strip() == condition:
            first_line = first_line.replace(condition or first_line, value)
        lines[0] = first_line
    with open(path, 'w') as file:
        file.write('\n'.join(lines))

# Change 'your_file.txt' to the name of your file
replace_first_line('your_file.txt', '1', condition='0')

【讨论】:

  • 谢谢。这工作得很好
猜你喜欢
  • 1970-01-01
  • 2011-11-21
  • 2015-12-18
  • 2020-12-17
  • 2013-09-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-14
相关资源
最近更新 更多