Python 模块2

标准库

fileinput

fileinput.input()       #返回能够用于for循环遍历的对象
fileinput.filename()    #返回当前文件的名称
fileinput.lineno()      #返回当前已经读取的行的数量(或者序号)
fileinput.filelineno()  #返回当前读取的行的行号
fileinput.isfirstline() #检查当前行是否是文件的第一行
fileinput.isstdin()     #判断最后一行是否从stdin中读取
fileinput.close()       #关闭队列

常见例子

  • 例子01: 利用fileinput读取一个文件所有行
[python]  view plain  copy
  1. >>> import fileinput  
  2. >>> for line in fileinput.input('data.txt'):  
  3.         print line,  
  4. #输出结果  
  5. Python  
  6. Java   
  7. C/C++  
  8. Shell  

命令行方式:

[python]  view plain  copy
  1. #test.py  
  2. import fileinput  
  3.   
  4. for line in fileinput.input():  
  5.     print fileinput.filename(),'|','Line Number:',fileinput.lineno(),'|: ',line  
  6.   
  7. c:>python test.py data.txt  
  8. data.txt | Line Number: 1 |:  Python  
  9. data.txt | Line Number: 2 |:  Java  
  10. data.txt | Line Number: 3 |:  C/C++  
  11. data.txt | Line Number: 4 |:  Shell  
  • 例子02: 利用fileinput对多文件操作,并原地修改内容
[python]  view plain  copy
  1. #test.py  
  2. #---样本文件---  
  3. c:\Python27>type 1.txt  
  4. first  
  5. second  
  6.   
  7. c:\Python27>type 2.txt  
  8. third  
  9. fourth  
  10. #---样本文件---  
  11. import fileinput  
  12.   
  13. def process(line):  
  14.     return line.rstrip() + ' line'  
  15.   
  16. for line in fileinput.input(['1.txt','2.txt'],inplace=1):  
  17.     print process(line)  
  18.   
  19. #---结果输出---  
  20. c:\Python27>type 1.txt  
  21. first line  
  22. second line  
  23.   
  24. c:\Python27>type 2.txt  
  25. third line  
  26. fourth line  
  27. #---结果输出---  
命令行方式:
[html]  view plain  copy
  1. #test.py  
  2. import fileinput  
  3.   
  4. def process(line):  
  5.     return line.rstrip() + ' line'  
  6.   
  7. for line in fileinput.input(inplace = True):  
  8.     print process(line)  
  9.   
  10. #执行命令  
  11. c:\Python27>python test.py 1.txt 2.txt  
  • 例子03: 利用fileinput实现文件内容替换,并将原文件作备份
[python]  view plain  copy
  1. #样本文件:  
  2. #data.txt  
  3. Python  
  4. Java  
  5. C/C++  
  6. Shell  
  7.   
  8. #FileName: test.py  
  9. import fileinput  
  10.   
  11. for line in fileinput.input('data.txt',backup='.bak',inplace=1):  
  12.     print line.rstrip().replace('Python','Perl')  #或者print line.replace('Python','Perl'),  
  13.       
  14. #最后结果:  
  15. #data.txt  
  16. Python  
  17. Java  
  18. C/C++  
  19. Shell  
  20. #并生成:  
  21. #data.txt.bak文件  
[python]  view plain  copy
  1. #其效果等同于下面的方式  
  2. import fileinput  
  3. for line in fileinput.input():  
  4.     print 'Tag:',line,  
  5.   
  6.   
  7. #---测试结果:     
  8. d:\>python Learn.py < data.txt > data_out.txt  
 
  • 例子04: 利用fileinput将CRLF文件转为LF
[python]  view plain  copy
  1. import fileinput  
  2. import sys  
  3.   
  4. for line in fileinput.input(inplace=True):  
  5.     #将Windows/DOS格式下的文本文件转为Linux的文件  
  6.     if line[-2:] == "\r\n":    
  7.         line = line + "\n"  
  8.     sys.stdout.write(line)  
  • 例子05: 利用fileinput对文件简单处理
[python]  view plain  copy
  1. #FileName: test.py  
  2. import sys  
  3. import fileinput  
  4.   
  5. for line in fileinput.input(r'C:\Python27\info.txt'):  
  6.     sys.stdout.write('=> ')  
  7.     sys.stdout.write(line)  
  8.   
  9. #输出结果     
  10. >>>   
  11. => The Zen of Python, by Tim Peters  
  12. =>   
  13. => Beautiful is better than ugly.  
  14. => Explicit is better than implicit.  
  15. => Simple is better than complex.  
  16. => Complex is better than complicated.  
  17. => Flat is better than nested.  
  18. => Sparse is better than dense.  
  19. => Readability counts.  
  20. => Special cases aren't special enough to break the rules.  
  21. => Although practicality beats purity.  
  22. => Errors should never pass silently.  
  23. => Unless explicitly silenced.  
  24. => In the face of ambiguity, refuse the temptation to guess.  
  25. => There should be one-- and preferably only one --obvious way to do it.  
  26. => Although that way may not be obvious at first unless you're Dutch.  
  27. => Now is better than never.  
  28. => Although never is often better than *right* now.  
  29. => If the implementation is hard to explain, it's a bad idea.  
  30. => If the implementation is easy to explain, it may be a good idea.  
  31. => Namespaces are one honking great idea -- let's do more of those!  
  • 例子06: 利用fileinput批处理文件
[python]  view plain  copy
  1. #---测试文件: test.txt test1.txt test2.txt test3.txt---  
  2. #---脚本文件: test.py---  
  3. import fileinput  
  4. import glob  
  5.   
  6. for line in fileinput.input(glob.glob("test*.txt")):  
  7.     if fileinput.isfirstline():  
  8.         print '-'*20'Reading %s...' % fileinput.filename(), '-'*20  
  9.     print str(fileinput.lineno()) + ': ' + line.upper(),  
  10.       
  11.       
  12. #---输出结果:  
  13. >>>   
  14. -------------------- Reading test.txt... --------------------  
  15. 1: AAAAA  
  16. 2: BBBBB  
  17. 3: CCCCC  
  18. 4: DDDDD  
  19. 5: FFFFF  
  20. -------------------- Reading test1.txt... --------------------  
  21. 6: FIRST LINE  
  22. 7: SECOND LINE  
  23. -------------------- Reading test2.txt... --------------------  
  24. 8: THIRD LINE  
  25. 9: FOURTH LINE  
  26. -------------------- Reading test3.txt... --------------------  
  27. 10: THIS IS LINE 1  
  28. 11: THIS IS LINE 2  
  29. 12: THIS IS LINE 3  
  30. 13: THIS IS LINE 4  
  • 例子07: 利用fileinput及re做日志分析: 提取所有含日期的行
[python]  view plain  copy
  1. #--样本文件--  
  2. aaa  
  3. 1970-01-01 13:45:30  Error: **** Due to System Disk spacke not enough...  
  4. bbb  
  5. 1970-01-02 10:20:30  Error: **** Due to System Out of Memory...  
  6. ccc  
  7.   
  8. #---测试脚本---  
  9. import re  
  10. import fileinput  
  11. import sys  
  12.   
  13. pattern = '\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}'  
  14.   
  15. for line in fileinput.input('error.log',backup='.bak',inplace=1):  
  16.     if re.search(pattern,line):  
  17.         sys.stdout.write("=> ")  
  18.         sys.stdout.write(line)  
  19.   
  20. #---测试结果---  
  21. => 1970-01-01 13:45:30  Error: **** Due to System Disk spacke not enough...  
  22. => 1970-01-02 10:20:30  Error: **** Due to System Out of Memory...  
  • 例子08: 利用fileinput及re做分析: 提取符合条件的电话号码
[python]  view plain  copy
  1. #---样本文件: phone.txt---  
  2. 010-110-12345  
  3. 800-333-1234  
  4. 010-99999999  
  5. 05718888888  
  6. 021-88888888  
  7.   
  8. #---测试脚本: test.py---  
  9. import re  
  10. import fileinput  
  11.   
  12. pattern = '[010|021]-\d{8}'  #提取区号为010或021电话号码,格式:010-12345678  
  13.   
  14. for line in fileinput.input('phone.txt'):  
  15.     if re.search(pattern,line):  
  16.         print '=' * 50  
  17.         print 'Filename:'+ fileinput.filename()+' | Line Number:'+str(fileinput.lineno())+' | '+line,  
  18.   
  19. #---输出结果:---  
  20. >>>   
  21. ==================================================  
  22. Filename:phone.txt | Line Number:3 | 010-99999999  
  23. ==================================================  
  24. Filename:phone.txt | Line Number:5 | 021-88888888  
  25. >>>   
  • 例子09: 利用fileinput实现类似于grep的功能
[python]  view plain  copy
  1. import sys  
  2. import re  
  3. import fileinput  
  4.   
  5. pattern= re.compile(sys.argv[1])  
  6. for line in fileinput.input(sys.argv[2]):  
  7.     if pattern.match(line):  
  8.         print fileinput.filename(), fileinput.filelineno(), line  
  9. $ ./test.py import.*re *.py  
  10. #查找所有py文件中,含import re字样的  
  11. addressBook.py  2   import re  
  12. addressBook1.py 10  import re  
  13. addressBook2.py 18  import re  
  14. test.py         238 import re  
  • 例子10: 利用fileinput做正则替换
[python]  view plain  copy
  1. #---测试样本: input.txt  
  2. * [Learning Python](#author:Mark Lutz)  
  3.       
  4. #---测试脚本: test.py  
  5. import fileinput  
  6. import re  
  7.    
  8. for line in fileinput.input():  
  9.     line = re.sub(r'\* 
    (.)(.∗)
    #(.*)#(.*)', r'<h2 id="\2">\1</h2>', line.rstrip())  
  10.     print(line)  
  11.   
  12. #---输出结果:  
  13. c:\Python27>python test.py input.txt  
  14. <h2 id="author:Mark Lutz">Learning Python</h2>  

  • 例子11: 利用fileinput做正则替换,不同字模块之间的替换
[python]  view plain  copy
  1. #---测试样本:test.txt  
  2. [@!$First]&[*%-Second]&[Third]  
  3.   
  4. #---测试脚本:test.py  
  5. import re  
  6. import fileinput  
  7.   
  8. regex = re.compile(r'^([^&]*)(&)([^&]*)(&)([^&]*)')  
  9. #整行以&分割,要实现[@!$First]与[*%-Second]互换  
  10. for line in fileinput.input('test.txt',inplace=1,backup='.bak'):  
  11.     print regex.sub(r'\3\2\1\4\5',line),  
  12.   
  13. #---输出结果:  
  14. [*%-Second]&[@!$First]&[Third]  
  • 例子12: 利用fileinput根据argv命令行输入做替换
[python]  view plain  copy
  1. #---样本数据: host.txt  
  2. # localhost is used to configure the loopback interface  
  3. # when the system is booting.  Do not change this entry.  
  4. 127.0.0.1      localhost  
  5. 192.168.100.2  www.test2.com  
  6. 192.168.100.3  www.test3.com  
  7. 192.168.100.4  www.test4.com  
  8.   
  9. #---测试脚本: test.py  
  10. import sys  
  11. import fileinput  
  12.   
  13. source = sys.argv[1]  
  14. target = sys.argv[2]  
  15. files  = sys.argv[3:]  
  16.   
  17. for line in fileinput.input(files,backup='.bak',openhook=fileinput.hook_encoded("gb2312")):  
  18.     #对打开的文件执行中文字符集编码  
  19.     line = line.rstrip().replace(source,target)  
  20.     print line  
  21.       
  22. #---输出结果:      
  23. c:\>python test.py 192.168.100 127.0.0 host.txt  
  24. #将host文件中,所有192.168.100转换为:127.0.0  
  25. 127.0.0.1  localhost  
  26. 127.0.0.2  www.test2.com  
  27. 127.0.0.3  www.test3.com  
  28. 127.0.0.4  www.test4.com  


time

在Python中,与时间处理有关的模块就包括:time,datetime以及calendar。这篇文章,主要讲解time模块。

在开始之前,首先要说明这几点:

  1. 在Python中,通常有这几种方式来表示时间:1)时间戳 2)格式化的时间字符串 3)元组(struct_time)共九个元素。由于Python的time模块实现主要调用C库,所以各个平台可能有所不同。

  2. UTC(Coordinated Universal Time,世界协调时)亦即格林威治天文时间,世界标准时间。在中国为UTC+8。DST(Daylight Saving Time)即夏令时。

  3. 时间戳(timestamp)的方式:通常来说,时间戳表示的是从1970年1月1日00:00:00开始按秒计算的偏移量。我们运行“type(time.time())”,返回的是float类型。返回时间戳方式的函数主要有time(),clock()等。

  4. 元组(struct_time)方式:struct_time元组共有9个元素,返回struct_time的函数主要有gmtime(),localtime(),strptime()。下面列出这种方式元组中的几个元素:


索引(Index)属性(Attribute)值(Values)
0 tm_year(年) 比如2011 
1 tm_mon(月) 1 - 12
2 tm_mday(日) 1 - 31
3 tm_hour(时) 0 - 23
4 tm_min(分) 0 - 59
5 tm_sec(秒) 0 - 61
6 tm_wday(weekday) 0 - 6(0表示周日)
7 tm_yday(一年中的第几天) 1 - 366
8 tm_isdst(是否是夏令时) 默认为-1

接着介绍time模块中常用的几个函数:

1)time.localtime([secs]):将一个时间戳转换为当前时区的struct_time。secs参数未提供,则以当前时间为准。

>>> time.localtime()
time.struct_time(tm_year=2011, tm_mon=5, tm_mday=5, tm_hour=14, tm_min=14, tm_sec=50, tm_wday=3, tm_yday=125, tm_isdst=0)
>>> time.localtime(1304575584.1361799)
time.struct_time(tm_year=2011, tm_mon=5, tm_mday=5, tm_hour=14, tm_min=6, tm_sec=24, tm_wday=3, tm_yday=125, tm_isdst=0)

2)time.gmtime([secs]):和localtime()方法类似,gmtime()方法是将一个时间戳转换为UTC时区(0时区)的struct_time。

>>>time.gmtime()
time.struct_time(tm_year=2011, tm_mon=5, tm_mday=5, tm_hour=6, tm_min=19, tm_sec=48, tm_wday=3, tm_yday=125, tm_isdst=0)

注意:这里的tm_wday=3表示的是周几,但是要在这个返回值的基础上往后推一天,即表示的是周四,而不是周三。

3)time.time():返回当前时间的时间戳。

>>> time.time() 
1304575584.1361799

4)time.mktime(t):将一个struct_time转化为时间戳。

>>> time.mktime(time.localtime())
1304576839.0

5)time.sleep(secs):线程推迟指定的时间运行。单位为秒。

6)time.clock():这个需要注意,在不同的系统上含义不同。在UNIX系统上,它返回的是“进程时间”,它是用秒表示的浮点数(时间戳)。而在WINDOWS中,第一次调用,返回的是进程运行的实际时间。而第二次之后的调用是自第一次调用以后到现在的运行时间。(实际上是以WIN32上QueryPerformanceCounter()为基础,它比毫秒表示更为精确)

[python]  view plain  copy
  1. import time    
  2. if __name__ == '__main__':    
  3.     time.sleep(1)    
  4.     print "clock1:%s" % time.clock()    
  5.     time.sleep(1)    
  6.     print "clock2:%s" % time.clock()    
  7.     time.sleep(1)    
  8.     print "clock3:%s" % time.clock()  


clock1:3.35238137808e-006 运行结果:

clock2:1.00004944763 
clock3:2.00012040636

其中第一个clock()输出的是程序运行时间
第二、三个clock()输出的都是与第一个clock的时间间隔

7)time.asctime([t]):把一个表示时间的元组或者struct_time表示为这种形式:'Sun Jun 20 23:21:05 1993'。如果没有参数,将会将time.localtime()作为参数传入。

>>> time.asctime()
'Thu May 5 14:55:43 2011'

8)time.ctime([secs]):把一个时间戳(按秒计算的浮点数)转化为time.asctime()的形式。如果参数未给或者为None的时候,将会默认time.time()为参数。它的作用相当于time.asctime(time.localtime(secs))。

>>> time.ctime()
'Thu May 5 14:58:09 2011'
>>> time.ctime(time.time())
'Thu May 5 14:58:39 2011'
>>> time.ctime(1304579615)
'Thu May 5 15:13:35 2011'

9)time.strftime(format[, t]):把一个代表时间的元组或者struct_time(如由time.localtime()和time.gmtime()返回)转化为格式化的时间字符串。如果t未指定,将传入time.localtime()。如果元组中任何一个元素越界,ValueError的错误将会被抛出。

格式含义备注
%a本地(locale)简化星期名称
%A本地完整星期名称
%b本地简化月份名称
%B本地完整月份名称
%c本地相应的日期和时间表示
%d一个月中的第几天(01 - 31)
%H一天中的第几个小时(24小时制,00 - 23)
%I第几个小时(12小时制,01 - 12)
%j一年中的第几天(001 - 366)
%m月份(01 - 12)
%M分钟数(00 - 59)
%p本地am或者pm的相应符
%S秒(01 - 61)
%U一年中的星期数。(00 - 53星期天是一个星期的开始。)第一个星期天之前的所有天数都放在第0周。
%w一个星期中的第几天(0 - 6,0是星期天)
%W和%U基本相同,不同的是%W以星期一为一个星期的开始。
%x本地相应日期
%X本地相应时间
%y去掉世纪的年份(00 - 99)
%Y完整的年份
%Z时区的名字(如果不存在为空字符)
%%‘%’字符

备注

  1. “%p”只有与“%I”配合使用才有效果。

  2. 文档中强调确实是0 - 61,而不是59,闰年秒占两秒(汗一个)。

  3. 当使用strptime()函数时,只有当在这年中的周数和天数被确定的时候%U和%W才会被计算。

举个例子:

>>> time.strftime("%Y-%m-%d %X", time.localtime())
'2011-05-05 16:37:06'

10)time.strptime(string[, format]):把一个格式化时间字符串转化为struct_time。实际上它和strftime()是逆操作。

>>> time.strptime('2011-05-05 16:37:06', '%Y-%m-%d %X')
time.struct_time(tm_year=2011, tm_mon=5, tm_mday=5, tm_hour=16, tm_min=37, tm_sec=6, tm_wday=3, tm_yday=125, tm_isdst=-1)

在这个函数中,format默认为:"%a %b %d %H:%M:%S %Y"

最后,我们来对time模块进行一个总结。根据之前描述,在Python中共有三种表达方式:1)timestamp 2)tuple或者struct_time 3)格式化字符串。

它们之间的转化如图所示:


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值