在python中处理空行时,经常会遇到一些问题。现总结经验如下:
1.遇到的空行如果只有换行符,直接使用=='\n'或者 len(line)==line.count('\n')
2.有多个空格+换行符时。有几种处理方法:①split; ②正则表达式'^\n'(不会);③if eachLine[:-1].strip()
展开:
eg.文件过滤,显示一个文件的所有行,忽略以井号(#)开头的行。
①
f=open('test.txt','r')
for eachLine in f:
if not eachLine.split(): # whether space
print eachLine,
elif eachLine.strip()[0]!='#':
print eachLine,
f.close()
③
f=open('test.txt','r')
for eachLine in f:
if not eachLine[:-1].strip():#whether space
print eachLine,
elif eachLine.strip()[0]!='#':
print eachLine,
f.close()
这两种方法都可以判断,
从同一台电脑上读取同样多行的字母,相对来说,第一种方法花费了8.4s,第三种方法花费了1.6s。从实验的角度上大概是第三种方法相对性能更优。
但