Skip to main content
 首页 » 编程设计

python:文本文件处理,for循环和read操作冲突

2025年05月04日11langtianya

我正在学习用 Python 编写代码。现在我正在试验来自 here 的文件比较程序。 .

我的代码是:

#!/usr/bin/python3 
 
def main(): 
    fhand1 = open('mbox.txt') 
    print('file handle for mbox is {}'.format(fhand1)) 
    count = 0 
    for l1 in fhand1: 
        count = count + 1 
        l1 = l1.rstrip()  # Skip 'uninteresting lines' 
        if l1.startswith('From:'): 
            print('{}'.format(l1)) 
    print('Numer of lines: {}'.format(count)) 
 
    fhand2 = open('mbox-short.txt') 
    #inp = fhand2.read(), when here for loop does not work 
    #for l2 in fhand2: 
        #if l2.startswith('From:'): 
            #print('{}'.format(l2)) 
    inp = fhand2.read()#if for loop is active then this doesnot work 
    print('Total characters in mbox-short: {}'.format(len(inp))) 
    print('First 20 characters on mbox-short: {}'.format(inp[:56])) 
 
if __name__ == "__main__": main() 

我的问题是关于“mbox-short.txt”的。当我将 inp = fhand2.read() 放在 for l2 in fhand2: {} 之前时,for 循环不会运行。当我更改序列时,read() 操作不起作用。

有人可以解释一下吗?

顺便说一句,我使用的是 JetBrains PyCharm Community Ed 4 IDE。

提前谢谢你。

请您参考如下方法:

这里发生的是读取操作在您分配变量时返回文件的完整内容(因此将插入符放在文件末尾),这就是您收到空字符串的原因。

你需要这样做:

fhand2 = open('mbox-short.txt') 
inp = fhand2.read() # uncomment the first read operation 
for l2 in fhand2: 
    if l2.startswith('From:'): 
        print('{}'.format(l2)) 
# inp = fhand2.read() comment out the second one 

或者这个:

fhand2 = open('mbox-short.txt') 
inp = fhand2.read() 
for l2 in fhand2: 
    if l2.startswith('From:'): 
        print('{}'.format(l2)) 
fhand2 = open('mbox-short.txt') # re-open the file you have already read 
inp = fhand2.read() 

查看有关 python i/o 的更多信息 here .