我有265個CSV文件,總記錄數超過400萬(行),需要在所有CSV文件中進行搜索和替換。我有我的PowerShell代碼下面,這是否一個片段,但它需要17分鐘,進行動作:在大型搜索/替換操作中PowerShell比較慢(比Python慢得多)?
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的情況下,但是,它仍然處理每個文件一氣呵成(它只是需要更多的代碼到那裏),所以我會想象,內存使用情況是「大約相同」......還是我錯過了什麼? :( – 2012-03-15 17:14:44
@pst我沒有測試,但它看起來像's = f.read()'加載到內存中,你也可以使用'$ reader.ReadToEnd()'PowerShell做到這一點。 – 2012-03-15 17:23:52
啊,我假設Get-Content是如何運作的: -/ – 2012-03-15 17:26:55