我试图在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")
但不断收到错误消息。请帮帮我:(
答案 0 :(得分: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