Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/356.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/unix/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
将某行文本替换为其他文本(python)已关闭_Python_Python 3.x_Replace - Fatal编程技术网

将某行文本替换为其他文本(python)已关闭

将某行文本替换为其他文本(python)已关闭,python,python-3.x,replace,Python,Python 3.x,Replace,我在其他论坛上尝试了很多其他的方法。但它们似乎都不起作用。也许我只是写错了。我有一个文本文件,我希望python将“0”替换为“1”。我的文本文件如下所示 0 hello more stuff meh 我希望是这样 1 hello more stuff meh 谢谢,这可能真的很简单。 如果有人可以发布一种方法,用1替换0或删除整行,然后重写它。任何一个都可以。 谢谢 我还希望它在0位于第三行或其他行时工作。当然,如果要替换文件第一行上的0,则必须更改其目标行: def replace_fi

我在其他论坛上尝试了很多其他的方法。但它们似乎都不起作用。也许我只是写错了。我有一个文本文件,我希望python将“0”替换为“1”。我的文本文件如下所示

0
hello
more stuff
meh
我希望是这样

1
hello
more stuff
meh
谢谢,这可能真的很简单。 如果有人可以发布一种方法,用1替换0或删除整行,然后重写它。任何一个都可以。 谢谢
我还希望它在0位于第三行或其他行时工作。当然,如果要替换文件第一行上的
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')

是否要将每个
0
替换为
1
?如果您有编号
10
,是否希望它变成
11
?我希望它只替换该行上的“0”,使其成为“1”(仅0本身),因此这不是您的编码服务,请编辑您的问题,并向我们展示您迄今为止的尝试。如果还没有,请使用。那么读取文本文件和解析值的代码在哪里?当然,你有一些出发点,在某个地方遇到了麻烦,而不是在这里找我们写另一个答案来阅读/编写文本文件,加入成千上万的现有答案?或者这个:谢谢。这很有效