2016-10-17 3 views
0

Hyは一緒に問題を抱えています。私は実際にやりたいことを説明します。私はいくつかのコンテンツを取得し、それをtxtファイルに書いてほしいと思うからphpファイルを含むいくつかのWebページフォルダを持つルートフォルダです。コードは実行され、エラーは出ませんが、必要なコンテンツを含むwords.txtファイルは作成されません。どんなアイデアなの?Pythonは異なるフォルダにあるファイルの内容を取得しています

from __future__ import print_function 
import io 
import os 
import re 

rootdir ='.../test' # I write here the full path but due to privacy reassons only the folders name 

for subdir, dirs, files in os.walk(rootdir): 
    for file in files: 
      if file.endswith(".php"): 
       with io.open(file, encoding="utf-8") as f, io.open('words.txt', 'w',encoding="utf-8") as g: 
        for line in f: 
         h = re.sub(r"$slimname = '([^']+)'", r"\1", line.rstrip()) 
         m = re.sub(r"'alwaysfound_text' => '([^']+)'", r"\1", line.rstrip()) 
         l = re.sub(r"'alwaysfound_place' => '([^']+)'", r"\1", line.rstrip()) 
         j = re.sub(r"'alwaysfound_job' => '([^']+)'", r"\1", line.rstrip()) 
         k = re.sub(r"var_keyword_hidden_generic' => '([^']+)'", r"\1", line.rstrip()) 
         print (h, m, l, j, k, file = g) 

答えて

2

コードでいくつかの問題:

  • あなたのために開いているファイル「w」はおそらくたい「」
  • インデントはマイナー混乱である(追記)が、問題
  • すべきではありません
  • ファイル名を開きますが、そのサブディレクトリは無視してください。with io.open(os.path.join(subdir, file), encoding="utf-8") as f
+0

これは今、おかげで多くの作品:D – Vedad

0

printステートメントと最初のブレースの間に空白があります。 これにより、構文エラーが発生するはずです。 コードを削除して、コードをもう一度テストしてください。

+1

いいえ、そうしてはいけません。ブラケットの前のスペースは問題ありません –

1

"file in files"というファイルを、モード "w"( "書き換え"を意味します)で開くと、次のファイルごとにword.txtファイルが書き換えられます。モード "a"( "追加"を意味する)を使用してみてください。

+0

これは実際には、ありがとう:) – Vedad

+0

しかし、それはまだフォルダの残りの部分を通過することはありません、それはちょうど最初のものを入力します。 – Vedad

関連する問題