【问题标题】:Why is this subprocess command not working?为什么这个子进程命令不起作用?
【发布时间】:2020-05-29 15:07:10
【问题描述】:

我正在尝试删除多个 txt 文件的每一行中的第一个和最后一个逗号。当我运行以下脚本时,in_files 没有任何更改(即逗号仍然存在)。我错过了什么?有没有更好的方法来做到这一点?

我从this thread 中找到了rev 命令。

我的脚本

import subprocess
from glob import glob

in_files = glob('path/to/files/*.txt')

for fyle in in_files:
    rr = f"rev {fyle} | cut -c2- | rev | cut -c2-"
    subprocess.check_output(['bash', '-c', rr])

in_files (file1.txt)

,-0.12000000000000000,0.0000000000000000,
,-0.11889999999999999,0.0000000000000000,
,-0.11780000000000000,0.0000000000000000,
,-0.11670000000000000,0.0000000000000000,
,-0.11559999999999999,0.0000000000000000,
,-0.11449999999999999,0.0000000000000000,

预期

-0.12000000000000000,0.0000000000000000
-0.11889999999999999,0.0000000000000000
-0.11780000000000000,0.0000000000000000
-0.11670000000000000,0.0000000000000000
-0.11559999999999999,0.0000000000000000
-0.11449999999999999,0.0000000000000000

【问题讨论】:

  • 为什么这被否决了?

标签: python-3.x subprocess


【解决方案1】:

您是否需要使用外部程序,或者这是否适合您的需要?

def trim(filename, new_filename):
    with open(filename) as infile:
        with open(new_filename, "w") as outfile:
            for line in infile:
                outfile.write(line.strip(",\n") + "\n")

file_list = ["file1.txt"]
for f in file_list:
    # btw if you want the original file to
    # be overwritten, call `trim(f, f)`
    trim(f, f+"_new.txt")

这会将您的预期输出写入文件。

【讨论】:

  • 这行得通,谢谢,但我仍然想知道为什么我的子进程命令不起作用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-09
  • 1970-01-01
  • 2011-06-14
  • 1970-01-01
  • 2019-03-25
相关资源
最近更新 更多