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

2024-04-20 09:55:03 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

代码运行得很好,我很好奇这是正确的方法还是有什么改进?你知道吗


Tags: 文件字符串代码txt内容ifaswith
1条回答
网友
1楼 · 发布于 2024-04-20 09:55:03

无需查找,如果第一行不是“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

这里有一种不将整个文件读入内存的替代模式(总是保持安静,考虑可伸缩性):

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

相关问题 更多 >