如何在文件读取时回退一行

1 投票
4 回答
2345 浏览
提问于 2025-04-16 11:14

在我的代码中,我有一行打印长度的代码,像这样:

line = file.readline()
print("length = ", len(line))

之后,我开始通过下面的方式扫描这些行:

for i in range(len(line)):
        if(file.read(1) == 'b'):
            print("letter 'b' found.")

问题是,for循环从文件的第二行开始读取。有没有办法让我从第一行开始读取,而不需要关闭再重新打开文件呢?

4 个回答

0
#! usr/bin/env python

#Open the file , i assumed its called somefile.txt
file = open('somefile.txt.txt','r')
#Lets loop through the lines ... 
for line in file.readlines():
    #test if letter 'b' is in each line ... 
    if 'b' in line: 
        #print that we found a b in the line
        print  "letter b found"

当然可以!请把你想要翻译的内容发给我,我会帮你用简单易懂的语言解释清楚。

1

看起来你需要特别处理第一行。

lineno = 1
found = False
for line in file:
    if 'b' in line:
        found = True

    if lineno == 1:
        print("length of first line: %d" % len(line))
    lineno += 1

if found:
    print("letter 'b' found.")
2

你可以使用 file.seek 来移动下一个读取的位置,但这样做效率不高。因为你已经读取了这一行,所以可以直接处理 line,而不需要再读一次。

with open(filename,'r') as f:
    line = f.readline()
    print("length = ", len(line))
    if 'b' in line:
        print("letter 'b' found.")

    for line in f: 
    ...

撰写回答