【发布时间】:2012-04-01 05:51:05
【问题描述】:
我有 265 个 CSV 文件,总记录(行)超过 400 万条,需要在所有 CSV 文件中进行搜索和替换。我在下面有一个我的 PowerShell 代码的 sn-p 可以执行此操作,但执行该操作需要 17 分钟:
ForEach ($file in Get-ChildItem C:\temp\csv\*.csv)
{
$content = Get-Content -path $file
$content | foreach {$_ -replace $SearchStr, $ReplaceStr} | Set-Content $file
}
现在我有以下 Python 代码,它执行相同的操作,但执行时间不到 1 分钟:
import os, fnmatch
def findReplace(directory, find, replace, filePattern):
for path, dirs, files in os.walk(os.path.abspath(directory)):
for filename in fnmatch.filter(files, filePattern):
filepath = os.path.join(path, filename)
with open(filepath) as f:
s = f.read()
s = s.replace(find, replace)
with open(filepath, "w") as f:
f.write(s)
findReplace("c:/temp/csv", "Search String", "Replace String", "*.csv")
为什么 Python 方法效率更高?是我的 PowerShell 代码效率低下,还是 Python 在文本操作方面只是一种更强大的编程语言?
【问题讨论】:
标签: python performance powershell replace