在Mac上使用Python打开文本文件

0 投票
1 回答
3431 浏览
提问于 2025-04-18 05:52

我正在Mac上用Python写一个程序,想让用户能搜索一个数据库。但是我在打开、查找或者读取附加的文本文件时遇到了问题。

我使用了:

import os
with open('a3-example-data.txt', 'r') as f:
    f.readline()
    for line in f:
        if 'Sample Text' in line:
            print "I have found it"
            f.seek(0)
            f.readline()
            for line in f:
                if 'Time Taken' in line:
                    print line
                    print ' '.join(line.split())
f.close()

还有

import os
file = open("/Users/moniv/Downloads/a3-example-data(2).txt", "r" "utf8")

但是总是出现错误信息。请帮帮我 :(

1 个回答

3

你的代码在很多地方都有问题,我猜错误出现在你回到主循环的时候,因为你回到了0,这导致主循环不同步。

# you do not need the os module in your code. Useless import
import os

with open('a3-example-data.txt', 'r') as f:
    ### the f.readline() is only making you skip the first line.
    ### Are you doing it on purpose?
    f.readline()
    for line in f:
        if 'Sample Text' in line:
            print "I have found it"
            ### seeking back to zero,
            f.seek(0)
            ### skipping a line
            f.readline()
            ### iterating over the file again, 
            ### while shadowing the current iteration
            for line in f:
                if 'Time Taken' in line:
                    print line
                    print ' '.join(line.split()) # why are you joining what you just split?
       ### and returning to the main iteration which will get broken
       ### because of the seek(0) within
       ### does not make much sense.

### you're using the context manager, so once you exit the `with` block, the file is closed
### no need to double close it!
f.close()

所以在不了解你想做什么的情况下,我对你的算法有一些看法:

import os
with open('a3-example-data.txt', 'r') as f:
    f.readline()
    for line in f:
        if 'Sample Text' in line:
            print "I have found it"
            break
    f.seek(0)
    f.readline()
    for line in f:
         if 'Time Taken' in line:
             print line

撰写回答