夫婦的評論:
首先,用with
打開一個文件通常是更好:
with open('Database.doc', 'r', encoding='latin-1') as f:
# closes the file automagically at the end of this block...
其次,沒有必要在整個文件中讀取,除非你正在做的事情與文件作爲一個整體。既然你正在尋找線,處理線逐一:
matches=[]
with open('Database.doc', 'r', encoding='latin-1') as f:
for line in f:
if string in line.lower():
matches.append(line)
如果你想匹配整個行:
matches=[]
with open('Database.doc', 'r', encoding='latin-1') as f:
for line in f:
if string == line.lower():
matches.append(line)
或者,更Pythonically,與列表理解:
with open('Database.doc', 'r', encoding='latin-1') as f:
matches=[line for line in f if line.lower()==string]
等等
'cardsDoc = wordsDoc'? – kojiro
你想要輸入的字符串匹配整個行還是隻是其中的一部分? – kojiro
對不起,cardsDoc = wordsDoc是的。我修正了這一點。 op_text是我需要搜索的輸入字符串。我想查看op_text中是否有與該文件中的整行匹配的子字符串,然後保存該子字符串。 – CrazyBurrito