Python 模块与面向对象编程实战
1. 模块导入基础
1.1 基本文件操作函数
在 Python 中,我们可以编写函数来统计文件的行数和字符数。以下是示例代码:
def countLines(name):
file = open(name)
return len(file.readlines())
def countChars(name):
return len(open(name).read())
def test(name):
return countLines(name), countChars(name)
使用示例:
import mymod
print(mymod.test('mymod.py'))
不过,上述函数会一次性将整个文件加载到内存中,对于过大的文件可能会导致内存不足。为了更健壮,可以逐行读取文件并计数:
def countLines(name):
tot = 0
for line in open(name):
tot += 1
return tot
def countChars(name):
tot = 0
for line in open(name):
tot += len(line)
return tot
超级会员免费看
订阅专栏 解锁全文

1645

被折叠的 条评论
为什么被折叠?



