【问题标题】:Replacing substring in every file in every directory and subdirectory替换每个目录和子目录中每个文件中的子字符串
【发布时间】:2020-09-23 19:27:21
【问题描述】:

我有一个使用 Python 2.7 的框架,我目前正在将其转换为 python 3。但是,有许多文件指向“C:\Python27...等”来获取某些脚本。我想遍历每个框架目录和子目录中的每个文件,并将文件中的这个子字符串“..\Python27..”更改为 Python38。 例如,我在 .bat 文件中有这个:

@echo off
setlocal
if not exist .\env27 (
  if not exist C:\Python27\Scripts\virtualenv.exe (
    echo VirtualEnv not found: C:\Python27\Scripts >&2
    exit /b 1
  )
  C:\Python27\Scripts\virtualenv .\env27
 ....

我想将 C:\Python27\Scripts\virtualenv.exe 替换为 C:\Python38\Scripts\virtualenv.exe

我已经尝试过这段代码Python - Way to recursively find and replace string in text files,但它适用于精确字符串而不是子字符串。到目前为止,这是我的代码:

import os, fnmatch

def findAndReplace(directory, find, replacement):
    for dname, dirs, files in os.walk(directory):
        for fname in files:
            fpath = os.path.join(dname, fname)
            with open(fpath) as f:
                s = f.read()
            s = s.replace(find, replacement)
            with open(fpath, "w") as f:
                f.write(s)


我想知道如何替换子字符串?

谢谢。

【问题讨论】:

  • 你能举一个你想替换的子字符串的例子吗?
  • 我刚刚在我的问题中添加了一个示例 ^。谢谢!
  • findreplacement 尝试了什么? s.replace(r"\Python27", r"\Python38") 没用?

标签: python python-3.x string replace python-2to3


【解决方案1】:

您可以使用re 搜索您需要的文本组。我鼓励您查看regex documentation,了解如何制作所需图案的详细信息。如果找到适合模式的特定子字符串不是问题,请澄清,因为这就是我从中得到的。

import os, re

for root, dirs, files in os.walk('path to directory'):
  for infile in files:
    with open(os.path.join(root, infile)) as in_text:
      contents = in_text.read()
    with open(os.path.join(root, infile), 'w') as out:
      out.write(re.sub(find, replacement, contents))

如果我没有涉及到更多细节,我很抱歉。如果是这种情况,请告诉我,我会尽力解决它!

【讨论】:

    猜你喜欢
    • 2020-02-21
    • 2021-11-26
    • 2021-10-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-24
    • 1970-01-01
    相关资源
    最近更新 更多