2017-10-11 26 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()