這裏是@Ashwini Chaudhary's answer Python 3的變種:
#!/usr/bin/env python3
import fileinput
import re
import sys
def main():
pattern, filename = sys.argv[1:] # get pattern, filename from command-line
matched = re.compile(pattern).search
with fileinput.FileInput(filename, inplace=1, backup='.bak') as file:
for line in file:
if not matched(line): # save lines that do not match
print(line, end='') # this goes to filename due to inplace=1
main()
它假定locale.getpreferredencoding(False) == 'utf-8'
否則可能對非ASCII字符突破。
爲了讓無論是什麼工作,當前區域是或有不同的編碼輸入文件:
#!/usr/bin/env python3
import os
import re
import sys
from tempfile import NamedTemporaryFile
def main():
encoding = 'utf-8'
pattern, filename = sys.argv[1:]
matched = re.compile(pattern).search
with open(filename, encoding=encoding) as input_file:
with NamedTemporaryFile(mode='w', encoding=encoding,
dir=os.path.dirname(filename)) as outfile:
for line in input_file:
if not matched(line):
print(line, end='', file=outfile)
outfile.delete = False # don't delete it on closing
os.replace(outfile.name, input_file.name)
main()
來源
2013-06-20 20:15:49
jfs
那麼,有什麼問題呢? – arshajii
您沒有閱讀文件。你需要像'inputfile.readlines()' – karthikr
這樣的東西你試圖關閉你從未打開過的2個文件,並且命名一個打開'inputfile'文件的文件最多隻會讓你感到困惑。 – geoffspear