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

Match first line using readline and read the file using seek if the pattern does not exist

我是 Python 的新手,正在尝试从文件中读取所有内容。如果第一行包含特定模式,我想从{second line, end of file}读取。如果模式不存在,我想读取整个文件。这是我写的代码。该文件在第 1 行中有 'Logs',在接下来的几行中有一些字符串。

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

代码运行良好,我很好奇这是正确的做法还是有任何改进?

不用查找,如果第一行不是"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

这里有一个替代模式,它不会将整个文件读入内存(总是 hust^H^H^H^H 考虑可伸缩性):

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