2017-10-04 4 views
0

私はPythonには新しく、ファイルからすべての内容を読み込もうとしています。最初の行に特定のパターンが含まれている場合は、{2行目、ファイルの最後}から読み込みたいと思います。もしパターンが存在しなければ、私はファイル全体を読みたいと思う。ここに私が書いたコードがあります。ファイルには、行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 

ここではファイル全体をメモリに読み込まない代替パターンは(常にhustことです^ 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 

ファイルが空である場合readline()方法も取り扱いをeschewingとわずかにより "神託":

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 
関連する問題