替换每个目录和子目录中每个文件中的子字符串

问题描述

我有一个使用Python 2.7的框架,目前正在将其转换为python3。但是,有许多文件直接指向“ 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)


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

谢谢。

解决方法

您可以使用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))

如果我没有涉及更多其他细节,很抱歉。请让我知道是否是这种情况,我会尽力解决这个问题!