を検索結果の文字列を書き込むために必要なファイルとオープンを読む:それは成功した最初の文字列を検索し、出力ファイルに合計数を書き込みます閉じる私は、次のコード持って再び出力ファイルに
import fileinput, os, glob, re
# Find text file to search in. Open.
filename = str(glob.glob('*.txt'))[2:][:-2]
print("found " + filename + ", opening...")
f = open(filename, 'r')
# Create output csv write total found occurrences of search string after name of search string
with open(filename[:-4] + 'output.csv','w') as output:
output.write("------------Group 1----------\n")
output.write(("String 1,") + str((len(re.findall(r's5 .*w249 w1025 w301 w1026 .*',f.read())))) +"\n")
output.write(("String 1 reverse,") + str((len(re.findall(r's5 .*w1026 w301 w1025 w249 .*',f.read())))) +"\n")
# close and finish
f.close
output.close
を、しかし、たとえそれが1000を見つけるべきであるとしても、 'String 1 reverse'のゼロの発見を書き込む。
それは私が文字列1と文字列1つの逆の検索の間にこれを挿入すると動作します。
f.close
f = open(filename, 'r')
つまり私は、読み取りファイルを閉じて、再度開きます。
各検索行の後にこれを追加する必要はありません。何が起こっているのですか?オープンファイルやキャッシュを正規表現でキャッシュすることと関係がありますか?
おかげ
'f.close()' 'ではないf.close' –