2017-09-22 3 views
0

ソースフォルダにあるすべてのファイルをgunzipするコードを書いています。しかし、私は、gunzippedファイルが存在しない場合はgunzipそれ以外の次のファイルに移動することを確認したい。Gunzip Pythonのソースディレクトリにあるすべてのファイル

source_dir = "/Users/path" 
dest_dir = "/Users/path/Documents/path" 


for src_name in glob.glob(os.path.join(source_dir, '*.gz')): 

    base = os.path.basename(src_name) 
    dest_name = os.path.join(dest_dir, base[:-3]) 
    with: gzip.open(src_name, 'rb') as infile, open(dest_name, 'wb') as outfile: 
      try: 
       for line in infile: 
        print ("outfile: %s" %outfile) 
        if not os.path.exists(dest_name): 
         outfile.write(line) 
         print("converted: %s" %dest_name) 

      except EOFError: 
       print("End of file error occurred.") 

      except Exception: 
       print("Some error occurred.") 

私は、ファイルが存在するかどうかをチェックするためにos.path.existを使用しているが、ここでは動作しませんos.path.existのように思えます。

+0

問題2については、OSのスケジュールされたジョブユーティリティを使用してください。自分でプログラムしようとする必要はありません。 – glibdud

+0

パート1には疑問はありません。パート2はスタックオーバーフローには広すぎます。 –

+0

@MadPhysicist、gunzippedファイルが存在しない場合はチェックを追加し、gunzipのみ他のwiseは次のファイルに移動します。これをチェックするには? – rnvs1116

答えて

1

私はあなたがpath.existsコールを間違って配置したと思います。それは次のようになります。

また
source_dir = "/Users/path" 
dest_dir = "/Users/path/Documents/path" 


for src_name in glob.glob(os.path.join(source_dir, '*.gz')): 

    base = os.path.basename(src_name) 
    dest_name = os.path.join(dest_dir, base[:-3]) 

    if not os.path.exists(dest_name): 
     with gzip.open(src_name, 'rb') as infile, open(dest_name, 'wb') as outfile: 
      try: 
       for line in infile: 
        print("outfile: %s" % outfile) 
        outfile.write(line) 
        print("converted: %s" % dest_name) 

      except EOFError: 
       print("End of file error occurred.") 

      except Exception: 
       print("Some error occurred.") 

@MadPhysicistが強調したよう:(あなたがあなたの元のコードで行ったように) は「(...、 『WB』)のオープン後にチェックをして、常にファイルが存在していることを言うだろうそれは開かれている(...、 'w')のためです」

さらに、ガンゾッピングの必要性について他のチェックをしたとしても、すべての行は完全に冗長であり、結果はすべての行で同じになります(存在する/存在しない)。

+0

OPのコードはあなたよりもはるかにエレガントです。 –

+0

私は既存のコードをあまり変更しませんでしたが、セットアップに必要なファイルのリストを使用する方法の例を示しました。私がしたのは、for_loopの前に5行追加することだけでした。もともとは彼が望むものを提供していなかった。 – ronenmiller

+0

@MadPhysicist最初にOPの質問が変わったのを見たことがありませんでした。私の答えを固定し、if文を置き忘れた。再確認し、あなたの考えを伝えてください。 – ronenmiller

関連する問題