2017-10-04 24 views
0

我是Python新手,试图读取文件中的所有内容。如果第一行包含特定模式,我想从{第二行,文件结束}读取。如果模式不存在,我想读取整个文件。这是我写的代码。该文件在第1行中有“日志”,在下一行中有一些字符串。使用readline匹配第一行,如果模式不存在,使用seek读取文件

with open('1.txt') as f: 
    if 'Logs' in f.readline(): 
     print f.readlines() 
    else: 
     f.seek(0) 
     print f.readlines() 

该代码工作正常,我很好奇,如果这是正确的方式做或有任何改进做到这一点?

回答

0

没有必要去追求,只是有条件地打印,如果第一行是不是“日志”:

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 

下面是不能读取整个文件到内存中的可选模式(永远是华中科大^ H^^ h^H ^伸缩性的Hthinking):

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 

略微更 “Python的” 通过避开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 
相关问题