1. 处理一个或多个文件的每一行:fileinput
模块
import fileinput, sys, string
# 从sys.argv 里取第一个参数并赋值给searchterm
searchterm, sys.argv[1:] = sys.argv[1], sys.argv[2:]
for line in fileinput.input():
num_matches = string.count(line,
searchterm)
if num_matches: # 大于零表示有匹配
print "found '%s' %d times in %s on line %d."%
(searchterm, +\ num_matches,fileinput.filename(),
fileinput.filelineno())
如果这个脚本称为mygrep.py,它可以这样用:
% python mygrep.py in *.py
found 'in' 2 times in countlines.py on line 2.
found 'in' 2 times in countlines.py on line 3.
found 'in' 2 times in mygrep.py on line 1.
found 'in' 4 times in mygrep.py on line 4.
found 'in' 2 times in mygrep.py on line 5.
found 'in' 2 times in mygrep.py on line 7.
found 'in' 3 times in mygrep.py on line 8.
found 'in' 3 times in mygrep.py on line 12.
2.
停止执行程序:sys.exit()
时间格式:time.strftime('%Y%m%d')
文件或目录是否存在:os.path.exists(target_dir)
创建目录: os.mkdir(target_dir)
当前目录:os.curdir
指定目录的文件名列表:os.listdir(目录名)
重命名:os.rename
例子:
import os, string
if len(sys.argv) == 1: # 如果没有指定目录
fil