Python - 使用subprocess调用sed?

13 投票
2 回答
24914 浏览
提问于 2025-04-16 21:36

我想在Python中通过subprocess来调用sed。我尝试的脚本如下。不过,这样做会把sed的输出直接显示在终端上。看起来在我的subprocess.call语句中,'>'这个操作符没有被识别。有什么建议吗?

import sys 
import os 
import subprocess

files = os.listdir(sys.argv[1])

count = 0

for f in files:
    count += 1
    inp = sys.argv[1] + f
    outp = '../' + str(count) + '.txt'
    sub = subprocess.call(['sed', 's/\"//g', inp, '>', outp])

另外,我的文件名中有空格,比如“ file1 .txt”。这会是问题吗?我在终端中直接调用sed命令时一切正常,但在脚本中就不行。

谢谢。

2 个回答

9

直接用Python来完成这个工作会快很多,而不是去运行所有的sed进程。

import os
import sys
files = os.listdir(sys.argv[1])

for count, f in enumerate(files):
    with open(os.path.join(sys.argv[1],f), "r") as source:
        with open(os.path.join('..',str(count)+'.txt'), "w") as target:
            data = source.read()
            changed = data.replace('"','')
            target.write(changed)

这样做会明显更快,因为它不会创建很多子进程。

15

使用

out_file = open(outp, "w")
sub = subprocess.call(['sed', 's/\"//g', inp], stdout=out_file )

撰写回答