with open('1.txt') as f:
line = f.readline()
if "Logs" not in line:
print line
print f.readlines() # read the rest of the lines
这里有一种不将整个文件读入内存的替代模式(总是保持安静,考虑可伸缩性):
with open('1.txt') as f:
line = f.readline()
if "Logs" not in line:
print line
for line in f:
# f is an iterator so this will fetch the next line until EOF
print line
稍微“pythonic”一点,如果文件为空,则避免使用readline()方法处理:
with open('1.txt') as f:
try:
line = next(f)
if "Logs" not in line:
print line
except StopIteration:
# if `f` is empty, `next()` will throw StopIteration
pass # you could also do something else to handle `f` is empty
for line in f:
# not executed if `f` is already EOF
print line
无需查找,如果第一行不是“Logs”,只需有条件地打印:
这里有一种不将整个文件读入内存的替代模式(总是保持安静,考虑可伸缩性):
稍微“pythonic”一点,如果文件为空,则避免使用
readline()
方法处理:相关问题 更多 >
编程相关推荐