眉若轻烟的BLOG 订阅
相关博文
内容读取中…
推荐博文
内容读取中…
谁看过这篇博文
内容读取中…
字体大小: 正文
python 笔记二 (2008-02-25 18:23:15)
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: # 如果没有指定目录
    filenames = os.listdir(os.curdir) # 就用当前目录
else: # 否则用命令行指定的目录
    filenames = sys.argv[1:]
for filename in filenames:
   if '' in filename:
     newfilename = string.replace(filename, '', '_')
     print "Renaming", filename, "to", newfilename, "..."
     os.rename(filename, newfilename)

 

3.os.system

formletter = """Dear %s,\nI'm writing to you to suggest that ...""" # 等等
myDatabase = [('Bill Clinton', 'bill@whitehouse.gov.us'),
('Bill Gates', 'bill@microsoft.com'),
('Bob', 'bob@subgenius.org')]
for name, email in myDatabase:
    specificLetter = formletter % name
    tempfilename = tempfile.mktemp()
    tempfile = open(tempfilename, 'w')
    tempfile.write(specificLetter)
    tempfile.close()
    os.system('/usr/bin/mail %(email)s -s "Urgent!"< %(tempfilename)s' % vars())
    os.remove(tempfilename)

注:tempfile.mktemp()(返回你机器的临时文件
目录(如Unix 里的/tmp 和Windows 的c:\tmp)中未使用的文件名,
)

 

 vars()
函数是一个内置函数,它返回对应于局部名字空间的变量的字典,字典的关键字
是变量名,字典的值是变量的值

在字符串中的%(...)s 部分的名字必须与程序里的变量名匹配

 

4.

#!/usr/bin/env python
# find files, search for tabs
import string, os
cmd = 'find . -name " * .py" -print' # find 是一个标准Unix 工具
for file in os.popen(cmd).readlines(): # 运行find 命令
num = 1
name = file[:-1] # 去掉'\n'
for line in open(name).readlines(): # 扫描文件
    pos = string.find(line, "\t")
    if pos >= 0:
      print name, num, pos # 报告找到的tab
      print '....', line[:-1] # [:-1]去掉最后的\n
      print '....', ''*pos + '*', '\n'
    num = num+1

 

os.popen
以一个shell 命令字符串作为参数,并返回一个链接到标准输入或标准输出
的文件对象,如果你没有给出一个"r"或"w"参数的话,缺省是标准输出。

 

string.find
在一个字符串里从左到右地找一个子串,并返回的一个位置的索引,我们用
它来找制表符,'\t'(转义的字符)。




 
评论(0)| 阅读 (0) | 收藏 (0) | 分享 | 打印 | 举报
发表评论
匿名评论(无需注册)
验证码:看不清楚数字吗?点击这里再试试。
新浪BLOG意见反馈留言板 不良信息反馈 电话:95105670 提示音后按2键(按当地市话标准计费) 欢迎批评指正

新浪简介 | About Sina | 广告服务 | 联系我们 | 招聘信息 | 网站律师 | SINA English | 会员注册 | 产品答疑

新浪公司 版权所有