我有以下代碼:關閉讀取文件並打開才能寫出搜索結果字符串輸出文件再次要求
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
它成功地找到了第一個字符串,並寫入總數到輸出文件,但它爲'String 1 reverse'寫入零查找,即使它應該找到1000。
f.close
f = open(filename, 'r')
即我關閉讀文件,然後再次打開它:
,如果我插入此搜索字符串1和字符串1個反向之間的作品。
我不想在每個搜索行之後添加這個,發生了什麼?這是否與在正則表達式中緩存打開的文件或緩存有關?
感謝
'f.close()''不f.close' –