使用readline匹配第一行,如果模式不存在,则使用seek读取文件

时间:2017-10-04 16:40:04

标签: python readlines

我是Python新手并尝试从文件中读取所有内容。如果第一行包含某个模式,我想从{第二行,文件末尾}读取。如果模式不存在,我想读取整个文件。这是我写的代码。该文件包含' Logs'在第1行和下一行中的一些字符串。

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

代码工作正常,我很好奇这是否是正确的方法或有任何改进来做到这一点?

1 个答案:

答案 0 :(得分:0)

如果第一行不是“Logs”,则无需寻找,只是有条件地打印:

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 of scalability):

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()方法稍微更加“pythonic”,如果文件为空也处理:

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