【发布时间】: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)
我想知道如何替换子字符串?
谢谢。
【问题讨论】:
-
你能举一个你想替换的子字符串的例子吗?
-
我刚刚在我的问题中添加了一个示例 ^。谢谢!
-
find和replacement尝试了什么?s.replace(r"\Python27", r"\Python38")没用?
标签: python python-3.x string replace python-2to3