用于搜索关键字的Python以文件

时间:2017-10-11 14:18:49

标签: python python-2.7

我的file1.txt有以下内容

if [ "x${GRUB_DEVICE_UUID}" = "x" ] || [ "x${GRUB_DISABLE_LINUX_UUID}" = "xtrue" ] \
   || ! test -e "/dev/disk/by-uuid/${GRUB_DEVICE_UUID}" \
   || uses_abstraction "${GRUB_DEVICE}" lvm; then
   LINUX_ROOT_DEVICE=${GRUB_DEVICE}
else
   LINUX_ROOT_DEVICE=UUID=${GRUB_DEVICE_UUID}
fi

GRUBFS="`${grub_probe} --device ${GRUB_DEVICE} --target=fs 2>/dev/null || true`"
Linux_CMDLINE="nowatchdog rcupdate.rcu_cpu_stall_suppress=1"

我想找到Linux_CMDLINE ="的字符串开头并用Linux_CMDLINE =""

替换该行

我尝试了以下代码,但它无效。我也认为这不是最好的实施方式。有没有简单的方法来实现这个目标?

with open ('/etc/grub.d/42_sgi', 'r') as f:
    newlines = []
    for line in f.readlines():
        if line.startswith('Linux_CMDLINE=\"'):
            newlines.append("Linux_CMDLINE=\"\"")
        else:
            newlines.append(line)

with open ('/etc/grub.d/42_sgi', 'w') as f:
    for line in newlines:
        f.write(line)

预期输出:

 if [ "x${GRUB_DEVICE_UUID}" = "x" ] || [ "x${GRUB_DISABLE_LINUX_UUID}" = "xtrue" ] \
   || ! test -e "/dev/disk/by-uuid/${GRUB_DEVICE_UUID}" \
   || uses_abstraction "${GRUB_DEVICE}" lvm; then
   LINUX_ROOT_DEVICE=${GRUB_DEVICE}
else
   LINUX_ROOT_DEVICE=UUID=${GRUB_DEVICE_UUID}
fi

GRUBFS="`${grub_probe} --device ${GRUB_DEVICE} --target=fs 2>/dev/null || true`"
Linux_CMDLINE=""

2 个答案:

答案 0 :(得分:2)

repl = 'Linux_CMDLINE=""'

with open ('/etc/grub.d/42_sgi', 'r') as f:
    newlines = []
    for line in f.readlines():
        if line.startswith('Linux_CMDLINE='):
            line = repl
        newlines.append(line)

答案 1 :(得分:1)

感谢open file for both reading and writing?

的最小代码
# Read and write (r+)
with open("file.txt","r+") as f:
    find = r'Linux_CMDLINE="'
    changeto = r'Linux_CMDLINE=""'
    # splitlines to list and glue them back with join
    newstring = ''.join([i if not i.startswith(find) else changeto for i in f])
    f.seek(0)
    f.write(newstring)
    f.truncate()