#普通写法是逐行读取文件内容,用“擂台赛”的方法获取最长的行:- f = open('a.txt', 'r')
- longest = 0
- while True:
- linelen = len(f.readline().strip())
- if not linelen:
- break
- if linelen > longest:
- longest = linelen
- f.close()
- print longest
复制代码 #考虑到尽早释放文件句柄,应该把关闭文件的操作提到前面:- f = open('a.txt', 'r')
- longest = 0
- allLines = f.readlines()
- f.close()
- for line in allLines:
- linelen = len(line.strip())
- if linelen > longest:
- longest = linelen
- print longest
复制代码 #使用列表解析在读取文件的时候就进行strip()处理- f = open('a.txt', 'r')
- longest = 0
- allLines = [x.strip() for x in f.readlines()]
- f.close()
- for line in allLines:
- linelen = len(line)
- if linelen > longest:
- longest = linelen
- print longest
复制代码 #使用迭代器获取长度的集合,避免readlines()读取所有行:- f = open('a.txt', 'r')
- allLineLens = [len(x.strip()) for x in f]
- f.close()
- print max(allLineLens)
复制代码 #用生成器表达式代替列表解析- f = open('a.txt', 'r')
- longest = max(len(x.strip()) for x in f)
- f.close()
- print longest
复制代码 #去掉文件打开模式(默认为读取):- print max(len(x.strip()) for x in open('a.txt'))
复制代码
|