[新手上路]批处理新手入门导读[视频教程]批处理基础视频教程[视频教程]VBS基础视频教程[批处理精品]批处理版照片整理器
[批处理精品]纯批处理备份&还原驱动[批处理精品]CMD命令50条不能说的秘密[在线下载]第三方命令行工具[在线帮助]VBScript / JScript 在线参考
返回列表 发帖

[技术讨论] 一行Python代码获取文件最长的行的长度

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

返回列表