with fileinput.input(files=("a.txt",), backup=".bak") as file: for line in file: print(f'{fileinput.filename()} 第{fileinput.lineno()}行: {line}', end='')
运行后,会多出一个备份文件:
1 2 3 4 5 6 7 8 9 10
$ ls -l a.txt* -rw-r--r-- 1 MING staff 12 2 27 10:43 a.txt
$ python demo.py a.txt 第1行: hello a.txt 第2行: world
$ ls -l a.txt* -rw-r--r-- 1 MING staff 12 2 27 10:43 a.txt -rw-r--r-- 1 MING staff 42 2 27 10:39 a.txt.bak
with fileinput.input(files=("a.txt",), inplace=True) as file: print("[INFO] task is started...") for line in file: print(f'{fileinput.filename()} 第{fileinput.lineno()}行: {line}', end='') print("[INFO] task is closed...")
运行后,会发现在 for 循环体内的 print 内容会写回到原文件中了。而在 for 循环体外的 print 则没有变化:
1 2 3 4 5 6 7 8 9 10 11
$ cat a.txt hello world
$ python demo.py [INFO] task is started... [INFO] task is closed...
for line in fileinput.input(files=('a.txt', ), inplace=True): #将Windows/DOS格式下的文本文件转为Linux的文件 if line[-2:] == "\r\n": line = line + "\n" sys.stdout.write(line)
结合re进行日志分析
1 2 3 4 5 6
#--样本文件--:error.log aaa 1970-01-01 13:45:30 Error: **** Due to System Disk spacke not enough... bbb 1970-01-02 10:20:30 Error: **** Due to System Out of Memory... ccc
1 2 3 4 5 6 7 8 9 10
import re import fileinput import sys
pattern = '\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}'
for line in fileinput.input('error.log',backup='.bak',inplace=1): if re.search(pattern,line): sys.stdout.write("=> ") sys.stdout.write(line)
1 2 3
#---测试结果--- => 1970-01-01 13:45:30 Error: **** Due to System Disk spacke not enough... => 1970-01-02 10:20:30 Error: **** Due to System Out of Memory...
实现类似grep功能
1 2 3 4 5 6 7 8
import sys import re import fileinput
pattern= re.compile(sys.argv[1]) for line in fileinput.input(sys.argv[2]): if pattern.match(line): print(fileinput.filename(), fileinput.filelineno(), line)
1 2 3 4 5 6
$ ./demo.py import.*re *.py #查找所有py文件中,含import re字样的 addressBook.py 2 import re addressBook1.py 10 import re addressBook2.py 18 import re test.py 238 import re