2017-10-11 22 views
0

我已经FILE1.TXT更换Python的搜索关键字开头,并在其下方有内容的文件

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="" 
+1

你什么输出? –

+0

有'else'的遗漏冒号 –

回答

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

最少的代码感谢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()