2017-10-04 21 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 
相關問題