2017-08-14 4 views
0

を検索結果の文字列を書き込むために必要なファイルとオープンを読む:それは成功した最初の文字列を検索し、出力ファイルに合計数を書き込みます閉じる私は、次のコード持って再び出力ファイルに

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') 

つまり私は、読み取りファイルを閉じて、再度開きます。

各検索行の後にこれを追加する必要はありません。何が起こっているのですか?オープンファイルやキャッシュを正規表現でキャッシュすることと関係がありますか?

おかげ

+1

'f.close()' 'ではないf.close' –

答えて

0

私はあなたの例をテストするためのサンプルを持っていないが、私は問題がから来ていると思われる:

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") 

あなたはファイル全体が読み込まれることを意味し、f.read() 2回行っています、カーソルがファイルの最後に設定されます。 2番目のf.read()は、読み取るデータがなくなるため、空の文字列を返します。

ファイルを読み取ると、nバイトを読み取った後、読み取りカーソル(ファイル記述子に添付されている位置)が+nバイトに変わることに注意してください。引数なしの場合、f.read()はファイルサイズのバイト全体を読み込み、ファイルの最後にカーソルを置きます。

  1. ストア変数(例:content = f.read())内のファイルの内容:

    は、次の2つのソリューションを持っているし、その変数に検索を行います。

  2. は、機能を追求ファイルを使用します。

を(、from_whatオフセット)f.seekを使用して、ファイルオブジェクトの位置を変更します。位置は、基準点へのオフセットを加算することによって計算される。参照点はfrom_what引数によって選択されます。 from_what値0はファイルの先頭から、1は現在のファイル位置を、2はファイルの終わりを参照ポイントとして使用します。 from_whatは省略することができ、ファイルの先頭を参照ポイントとして使用してデフォルトの0になります。

https://docs.python.org/3/tutorial/inputoutput.html

最初のソリューションは、実際には推奨されます:あなたは複数回ファイルを読む必要はありません、と求めている機能は、主に大規模なファイル操作のために使用されています。ここで

はその勧告、次のコードの修正バージョンです:

import fileinput, os, glob, re 

# Find text file to search in. Open. 
filename = str(glob.glob('*.txt'))[2:][:-2] 
print("found " + filename + ", opening...") 
content = open(filename, 'r').read() 

# 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 .*',content)))) +"\n") 
    output.write(("String 1 reverse,") + str((len(re.findall(r's5 .*w1026 w301 w1025 w249 .*',content)))) +"\n") 

最適化:あなたはファイルインスタンスの一切の参照を保持しないよう、あなたが、今の変数にclose()する必要はありません。

0

file.read()を実行すると、ファイル全体が読み込まれ、ポインタはファイルの最後にあります。 2行目が結果を返さないのはこのためです。

あなたの分析を実行し、最初の内容を読み取るために必要があります。

print("found " + filename + ", opening...") 
f = open(filename, 'r') 
contents = f.read() 
f.close() # -- note f.close() not f.close 

results_a = re.findall(r's5 .*w249 w1025 w301 w1026 .*',contents) 
results_b = re.findall(r's5 .*w1026 w301 w1025 w249 .*',contents) 

with open(filename[:-4] + 'output.csv','w') as output:  
    output.write("------------Group 1----------\n") 
    output.write("String 1 {}\n".format(len(results_a))) 
    output.write("String 1 reverse, {}\n".format(len(results_b))) 

文を使用して、自動的に閉じますとあなたは、(それが最初の場所で何もしませんでした)output.closeを必要としません。ファイル。

あなたのパターンに一致するすべてのファイルに対してこの操作を繰り返したい場合:

import glob 
import re 
import os 

BASE_DIR = '/full/path/to/file/directory' 

for file in glob.iglob(os.path.join(BASE_DIR, '*.txt')): 
    with open(file) as f: 
    contents = f.read() 
    filename = os.path.splitext(os.path.basename(f))[0] 
    results_a = re.findall(r's5 .*w249 w1025 w301 w1026 .*',contents) 
    results_b = re.findall(r's5 .*w1026 w301 w1025 w249 .*',contents) 
    with open(os.path.join(BASE_DIR, '{}output.csv'.format(filename), 'w') as output: 
     output.write("------------Group 1----------\n") 
     output.write("String 1 {}\n".format(len(results_a))) 
     output.write("String 1 reverse, {}\n".format(len(results_b))) 
関連する問題