1)私は、ファイルPython 3 re.findall closing file?</p> <p>3期待通りのリストを返す<code>re.findall()</code>
2を開く)の実行)、その後、私はre.findall()
を実行するには、再度、他の何かを探しているが、それは空のリストを返します。
しかし、2と3の間でもう一度ファイルを開くと、2番目のre.findall()
が完全に機能します。
何が起こっているのかわからないのですが、re
はファイルを閉じていますか?何か他に起こっていることはありますか?
ご協力いただきありがとうございます。
ここに私のコードだ
def extract_names(filenames):
for f in filenames: #grabs one file at a time
file = open(f, 'r') #opens file
#find year <h3 align="center">Popularity in 1992</h3>
year = re.search(r'Popularity\sin\s\d{4}', file.read())
print(year)
file = open(f, 'r') #reopen file
#find <tr align="right"><td>1</td><td>Michael</td><td>Ashley</td>
rank_names = re.search(r'<td>\d*</td><td>\w*</td><td>\w*</td>', file.read())
print(rank_names)
最初にHtmlパーサを使用します。あなたの問題については、同じファイルハンドラに対して 'file.read()'を2回使用することはできません(最初に読み込まれると2回目の読み込みはそれ以上ありません)。 –