python 文件输入查找和替换行

python fileinput find and replace line

我正在尝试查找以特定字符串开头的行并将整行替换为新字符串

我试过这个代码


filename = "settings.txt"
for line in fileinput.input(filename, inplace=True):
    print line.replace('BASE_URI =', 'BASE_URI = "http://example.net"')

这不是替换整行,而是替换一个匹配的字符串。替换以字符串开头的整行的最佳方法是什么?

你不需要知道 old 是什么;只需重新定义整行:

import sys
import fileinput
for line in fileinput.input([filename], inplace=True):
    if line.strip().startswith('BASE_URI ='):
        line = 'BASE_URI = "http://example.net"\n'
    sys.stdout.write(line)

您使用的是 python 2 语法吗?由于 python 2 已停产,我将尝试在 python 3 语法

中解决此问题

假设您需要将以“Hello”开头的行替换为“Not Found”,那么您可以做的是

lines = open("settings.txt").readlines()
newlines = []
for line in lines:
    if not line.startswith("Hello"):
        newlines.append(line)
    else:
        newlines.append("Not Found")
with open("settings.txt", "w+") as fh:
    for line in newlines:
        fh.write(line+"\n")

这应该可以解决问题:

def replace_line(source, destination, starts_with, replacement):

    # Open file path
    with open(source) as s_file:
        # Store all file lines in lines
        lines = s_file.readlines()
        # Iterate lines
        for i in range(len(lines)):
            # If a line starts with given string
            if lines[i].startswith(starts_with):
                # Replace whole line and use current line separator (last character (-1))
                lines[i] = replacement + lines[-1]

    # Open destination file and write modified lines list into it
    with open(destination, "w") as d_file:
        d_file.writelines(lines)

使用此参数调用它:

replace_line("settings.txt", "settings.txt", 'BASE_URI =', 'BASE_URI = "http://example.net"')

干杯!