繁体   English   中英

如何用 python 替换文件的特定行?

[英]How do you replace a specific line of a file with python?

line_row = -1
file = open(file_path, 'r')
for number_of_lines in file:
    line_row = line_row + 1
    if '1234' in number_of_lines:
        lines = file.readlines()
        line = lines[line_row]
        print(lines)
        lines[line_row] = 'hello'
        file = open(file_path, "w")
        file.writelines(lines)
        file.close()

当我运行它时,它将删除第 n 行之前的所有内容。 我希望它只替换第 n 行。 你能帮助我吗?

试试这个,使用enumerate

with open(file_path, 'r') as f:
    lines = f.readlines()
    for i, line in enumerate(lines):
        if "some text" in line:
            lines[i] = "updated text"

with open(file_path, "w") as f:
    f.writelines(lines)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM