如何在文件读取期间更改一行

时间:2011-02-04 17:24:18

标签: python io line

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

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

之后我开始扫描这些行:

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

问题是for循环开始在文件的第2行读取。 如何在第1行开始阅读而不关闭并重新打开文件?

4 个答案:

答案 0 :(得分: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: 
    ...

答案 1 :(得分: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 :(得分:0)

听起来你想要这样的东西:

with open('file.txt', 'r') as f:
    for line in f:
        for character in line:
            if character == "b":
                print "letter 'b' found."

或者如果您只需要数字:

with open('file.txt', 'r') as f:
    b = sum(1 for line in f for char in line if char == "b")
print "found %d b" % b

答案 3 :(得分: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"