- 标准输出显示文本名以及行号:
!/usr/bin/env python3
import fileinput
with fileinput.input('1.ttt') as f_input:
for line in f_input:
print(f_input.filename(),f_input.lineno(),line,end='')
- 替换文件内容并备份:
!/usr/bin/env python3
import fileinput
for line in fileinput.input('1.ttt',backup='.bak',inplace=1):
print(line.rstrip().replace('asd','Perl')) #将1.ttt文件中的asd替换成Perl
3.在指定文本的每一行的最前面加上‘=>’
!/usr/bin/env python3
import sys
import fileinput
for line in fileinput.input(r'/home/liujiangbu/hhhhhhh/1.ttt'):
sys.stdout.write('=> ')
sys.stdout.write(line)
- 将小写改成大写:
!/usr/bin/env python3
import fileinput
import glob
for line in fileinput.input(glob.glob("1.ttt")):
if fileinput.isfirstline():
print('-'20, 'Reading %s...' % fileinput.filename(), '-'20)
print(str(fileinput.lineno()) + ': ' + line.upper())
glob主要方法就是glob,该方法返回所有匹配的文件路径列表,该方法需要一个参数用来指定匹配的路径字符串(本字符串可以为绝对路径也可以为相对路径),比如:
import glob
glob.glob(r'c:/.txt')
我这里就是获得C盘下的所有txt文件
glob.glob(r'E:/pic//*.jpg')
获得指定目录下的所有jpg文件
- 利用fileinput及re做日志分析,提取所有含日期的行:
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)
---测试结果---
=> 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...
=====================此处设计的re模块:
import re
将正则表达式编译成Pattern对象
pattern = re.compile(r'hello')
使用Pattern匹配文本,获得匹配结果,无法匹配时将返回None
match = pattern.match('hello world!')
if match:
# 使用Match获得分组信息
print match.group()
输出
hello
re提供了众多模块方法用于完成正则表达式的功能。这些方法可以使用Pattern实例的相应方法替代,唯一的好处是少写一行re.compile()代码,但同时也无法复用编译后的Pattern对象。这些方法将在Pattern类的实例方法部分一起介绍。如上面这个例子可以简写为:
m = re.match(r'hello', 'hello world!')
print m.group()
- 利用fileinput根据argv命令行输入做替换:
---样本数据: host.txt
localhost is used to configure the loopback interface
when the system is booting. Do not change this entry.
127.0.0.1 localhost
192.168.100.2 www.test2.com
192.168.100.3 www.test3.com
192.168.100.4 www.test4.com
---测试脚本: test.py
import sys
import fileinput
source = sys.argv[1]
target = sys.argv[2]
files = sys.argv[3:]
for line in fileinput.input(files,backup='.bak',openhook=fileinput.hook_encoded("gb2312")):
#对打开的文件执行中文字符集编码
line = line.rstrip().replace(source,target)
print line
---输出结果:
c:>python test.py 192.168.100 127.0.0 host.txt
将host文件中,所有192.168.100转换为:127.0.0
127.0.0.1 localhost
127.0.0.2 www.test2.com
127.0.0.3 www.test3.com
127.0.0.4 www.test4.com
此处涉及到的rstrip方法:
返回值
返回删除 string 字符串末尾的指定字符后生成的新字符串。
实例
以下实例展示了rstrip()函数的使用方法:
!/usr/bin/python
str = " this is string example....wow!!! ";
print str.rstrip();
str = "88888888this is string example....wow!!!8888888";
print str.rstrip('8');
以上实例输出结果如下:
this is string example....wow!!!
88888888this is string example....wow!!!
- 读取配置文件:
假如内容如下:
; config.ini
; Sample configuration file
[installation]
library=%(prefix)s/lib
include=%(prefix)s/include
bin=%(prefix)s/bin
prefix=/usr/local
Setting related to debug configuration
[debug]
log_errors=true
show_warnings=False
[server]
port: 8080
nworkers: 32
pid-file=/tmp/spam.pid
root=/www/root
signature:
=================================
Brought to you by the Python Cookbook
=================================
读取其中的值:
from configparser import ConfigParser
cfg = ConfigParser()
cfg.read('config.ini')
['config.ini']
cfg.sections()
['installation', 'debug', 'server']
cfg.get('installation','library')
'/usr/local/lib'
cfg.getboolean('debug','log_errors')
True
修改配置使用 cfg.write() 方法将其写回到文件中:
cfg.set('server','port','9000')
cfg.set('debug','log_errors','False')
import sys
cfg.write(sys.stdout)
- 开启日志跟踪:
import logging
def main():
# Configure the logging system
logging.basicConfig(
filename='app.log',
level=logging.ERROR #日志等级:critical,error,warning,info,debug
)
# Variables (to make the calls that follow work)
hostname = 'www.python.org'
item = 'spam'
filename = 'data.csv'
mode = 'r'
# Example logging calls (insert into your program)
logging.critical('Host %s unknown', hostname)
logging.error("Couldn't find %r", item)
logging.warning('Feature is deprecated')
logging.info('Opening file %r, mode=%r', filename, mode)
logging.debug('Got here')
if name == 'main':
main()
上面五个日志调用(critical(), error(), warning(), info(), debug())以降序方式表示不同的严重级别。 basicConfig() 的 level 参数是一个过滤器。 所有级别低于此级别的日志消息都会被忽略掉。 每个 logging 操作的参数是一个消息字符串,后面再跟一个或多个参数。 构造最终的日志消息的时候我们使用了%操作符来格式化消息字符串。
面的日志配置都是硬编码到程序中的。如果你想使用配置文件, 可以像下面这样修改 basicConfig() 调用:
import logging
import logging.config
def main():
# Configure the logging system
logging.config.fileConfig('logconfig.ini')
...
创建一个下面这样的文件,名字叫 logconfig.ini:
[loggers]
keys=root
[handlers]
keys=defaultHandler
[formatters]
keys=defaultFormatter
[logger_root]
level=INFO
handlers=defaultHandler
qualname=root
[handler_defaultHandler]
class=FileHandler
formatter=defaultFormatter
args=('app.log', 'a')
[formatter_defaultFormatter]
format=%(levelname)s:%(name)s:%(message)s
如果你想修改配置,可以直接编辑文件 logconfig.ini 即可。
网友评论