【问题标题】:Output redirection to multiple files输出重定向到多个文件
【发布时间】:2016-11-27 15:17:05
【问题描述】:

我需要为多个输入文件运行一个 python 脚本,并且为每个输入文件生成一个新的相应输出文件(例如,对于 input_16jun.txt,我希望输出文件为 16jun_output.txt)。我尝试做类似的事情:

nohup python script.py input_{16..22}jun.txt > {16..22}jun_output.txt &

但我不断收到“模糊重定向”错误。有谁知道如何解决这一问题?还是有其他更好的方法?

【问题讨论】:

  • 试试这个 - nohup python script.py input_{16..22}jun.txt |三通 {16..22}jun_output.txt &
  • 还是同样的错误:/
  • 刚刚更新。如果有效就试试吧
  • 看起来只为一个输入文件运行脚本并在每个输出文件中存储相同的输出
  • 我认为您的输入和输出文件名在每次迭代中都会发生变化? tee 会覆盖文件中的内容。

标签: python bash redirect


【解决方案1】:

像这样使用 bash 遍历每个输入文件应该可以工作。

for f in input_*.txt; do python script.py $f > "${f:6:-4}"_output.txt; done

或者,如果您想在 python 脚本中执行循环。

import glob
import os

input_files = glob.glob("input_*.txt")

for f in input_files:
    os.system("python script.py {} > {}_output.txt".format(f,f.split("input_")[1].rstrip(".txt")))

如果您想并行(而不是按顺序)运行 script.py,您还可以考虑使用 python multiprocessing 包。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-06
    • 1970-01-01
    • 1970-01-01
    • 2012-09-12
    相关资源
    最近更新 更多