Python从位于不同文件夹中的文件中获取内容

时间:2016-10-17 13:49:44

标签: python-3.x

Hy在一起,我的代码有问题,因为它没有做它应该做的事情。我将描述我想要做的事情。我有文件夹caled测试是一个根文件夹与几个网页文件夹包含php文件,我希望得到一些内容,并将其写入txt文件。代码运行并且不会给出任何错误,但它也不会创建带有我想要的内容的words.txt文件。任何想法为什么?

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)

3 个答案:

答案 0 :(得分:2)

代码的一些问题:

  • 你打开文件' w'但可能想要' a' (追加)
  • 缩进是轻微的混乱,但不应该是一个问题
  • 您打开文件名但忽略其子目录 - 使用with io.open(os.path.join(subdir, file), encoding="utf-8") as f

答案 1 :(得分:1)

您可能会为每个下一个" file in files"重写文件word.txt。当你用模式" w"打开它时(这意味着"重写")。尝试使用模式" a" (这意味着"追加")。

答案 2 :(得分:0)

我在print语句和第一个大括号之间找到了一个空白。 这应该导致语法错误。 删除它并再次测试您的代码。