Python 官方文档:入门教程 => 点击学习
模拟wc命令统计行和字符的功能。 # vim wc.py #!/usr/bin/env python ''' Author:diege Email:diege@foxmail.com Date
模拟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
--结束END--
本文标题: Python实战(1)模拟wc命令部分功
本文链接: https://lsjlt.com/news/186500.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
2024-03-01
2024-03-01
2024-03-01
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0