【问题标题】:Find fileS and then find a string in those files查找 fileS,然后在这些文件中查找字符串
【发布时间】:2016-07-12 11:58:06
【问题描述】:

我编写了一个函数来查找路径中的所有 version.php 文件。我正在尝试获取该函数的输出并从该文件中找到一行。查找文件的函数是:

def find_file():
  for root, folders, files in os.walk(acctPath):
    for file in files:
      if file == 'version.php':
        print os.path.join(root,file)
find_file()

路径中有几个 version.php 文件,我想从每个文件中返回一个字符串。

编辑: 感谢您的建议,我的代码实现不符合我的需要。我能够通过创建一个列表并将每个项目传递给第二部分来解决这个问题。这可能不是最好的方法,我只做了几天python。

def cmsoutput():
  fileList = []
  for root, folders, files in os.walk(acctPath):
    for file in files:
      if file == 'version.php':
        fileList.append(os.path.join(root,file))

  for path in fileList:
    with open(path) as f:
      for line in f:
        if line.startswith("$wp_version ="):
          version_number = line[15:20]
          inst_path = re.sub('wp-includes/version.php', '', path)
          version_number = re.sub('\';', '', version_number)
          print inst_path + " = " + version_number

cmsoutput()

【问题讨论】:

  • 你想返回哪个字符串?基于什么标准?
  • 我要找的字符串是"$wp_version=",除了它的存在没有其他条件。

标签: python wordpress content-management-system cpanel


【解决方案1】:

既然你想使用你的函数的输出,你必须return 一些东西。打印它不会剪切它。假设一切正常,它必须稍微修改如下:

import os


def find_file():
    for root, folders, files in os.walk(acctPath):
        for file in files:
            if file == 'version.php':
                return os.path.join(root,file)

foundfile = find_file()

现在变量foundfile 包含我们要查看的文件的路径。然后可以像这样在文件中查找字符串:

with open(foundfile, 'r') as f:
    content = f.readlines()
    for lines in content:
        if '$wp_version =' in lines:
            print(lines)

或者在函数版本中:

def find_in_file(string_to_find, file_to_search):
    with open(file_to_search, 'r') as f:
        content = f.readlines()
        for lines in content:
            if string_to_find in lines:
                return lines

# which you can call it like this:
find_in_file("$wp_version =", find_file())

请注意,上述代码的函数版本将在找到您要查找的字符串的一个实例后立即终止。如果你想得到它们,它必须被修改。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-10
    • 1970-01-01
    相关资源
    最近更新 更多