【发布时间】:2020-01-22 06:05:33
【问题描述】:
我编写了一个 python 脚本来快速读取和替换文件夹中的多个文本文件(以 Gb 为单位)。有没有办法比我的脚本更快地做到这一点?是否可以为此脚本专用多个 cpu 内核脚本运行?
import re
import os
drc = '/root/tmp'
pattern = re.compile('"')
oldstr = '"'
newstr = ''
for dirpath, dirname, filename in os.walk(drc):
for fname in filename:
path = os.path.join(dirpath, fname)
strg = open(path).read()
if re.search(pattern, strg):
strg = strg.replace(oldstr, newstr)
f = open(path, 'w')
f.write(strg)
f.close()
【问题讨论】:
-
如果你在linux上,你可以使用
sed。 -
@sshashank124 以前我使用了一个 sed 脚本,但它比这个 python 脚本慢。我知道 python 脚本比 bash 脚本要快。
-
@sshashank124 #!/bin/bash cd "/root/tmp" sed -i -e 's/"//g' *.TXT rm *.TXTe
-
@Sushant 我不知道在给定链接中使用哪个是正确的?