模拟wc命令统计行和字符的功能。
# vim wc.py
- #!/usr/bin/env python
- '''
- Author:diege
- Email:diege@foxmail.com
- Date:2012-03-04
- Useage:wc.py filename
- '''
- #import sys
- #filename=raw_input('Enter FileName:')
- #filename=sys.argv[1]
- from sys import argv as getargv
- filename=getargv[1]
- def CountLines(filename):
- countlines=''
- countlines=len(open(filename).readlines())
- return countlines
- def ConutChars(filename):
- conutchars=''
- conutchars=len(open(filename).readlines())
- return conutchars
- def GetFileInfo(filename):
- countlines=CountLines(filename)
- conutchars=ConutChars(filename)
- print 'file:%s,line:%s,chars:%s' %(filename,countlines,conutchars)
- if __name__=='__main__':
- '''
- #debug
- print filename
- countlines=len(open(filename).readlines())
- conutchars=len(open(filename).readlines())
- print 'file:%s,line:%s,chars:%s' %(filename,countlines,conutchars)
- '''
- GetFileInfo(filename)
总结:
犯了两个错误
1、open(filename) 传入的是变量filename 不要写成open('filename'),不然传入的就是字符串不是变量了
2、关于函数内,本地变量的未定义的问题。
忘记在函数内定义本地变量countlines和conutchars,结果报错变量没有定义。
- # python wc.py module.py
- Traceback (most recent call last):
- File "wc.py", line 25, in <module>
- GetFileInfo(filename)
- File "wc.py", line 15, in GetFileInfo
- conutchars=ConutChars(filename)
- File "wc.py", line 12, in ConutChars
- return countlines
- NameError: global name 'countlines' is not defined