【问题标题】:How to run "cat file1 | tr -d '\r' > file2" in Python? [duplicate]如何在 Python 中运行“cat file1 | tr -d '\r' > file2”? [复制]
【发布时间】:2018-07-03 00:06:19
【问题描述】:

在 Python 中调用以下 unix 命令的最佳方法是什么? cat file1.txt | tr -d '\r' > file2.txt 我尝试了以下案例:
1.

cmd = "cat file1 | tr -d \'\r\'> file2"
args = shlex.split(cmd)
p = subprocess.Popen(args, shell=True)

我收到了cat: stdin: Input/output error

2.

f = open(file2, "w")
p = subprocess.call(args, stdout=f)

我明白了:

cat: |: No such file or directory
cat: tr: No such file or directory
cat: -d: No such file or directory
cat: \r: No such file or directory

3.

p = subprocess.Popen(args, stdout=subprocess.PIPE)
(out,err) = p.communicate()
print(out)

它有效,但我不知道为什么当我使用 file.write(out) 而不是 print(out) 时,我得到与案例 2 相同的错误。

【问题讨论】:

  • 我可能会被告知按要求回答问题,但是:没有理由使用 Python 中的 cat 和 tr 来删除回车符。打开文件,读取数据,并转换后写出。
  • @Ned Batchelder,文件可能很大,所以我不想在 python 中打开和编辑它。
  • @Shabnam 您不必将所有数据都保存在内存中。你的 Python 程序可以做 tr 做的事情。

标签: python


【解决方案1】:

只需在 Python 中完成:

with open("file1.txt", "rb") as fin:
    with open("file2.txt", "wb") as fout:
        while True:
            data = fin.read(100000)
            if not data:
                break
            data = data.replace(b"\r", b"")
            fout.write(data)

【讨论】:

  • 在这里做fin.read(fin._CHUNK_SIZE) 会有用吗?自从我注意到文件有一个_CHUNK_SIZE 属性后,我就预感到这个值可能会针对最佳磁盘读取操作进行优化,但从来没有真正在精神上证明它是合理的,因为这意味着在 python-land 中进行更多的迭代。
  • 我从来没有 _CHUNK_SIZE 的标题,也不知道它会如何影响事情。我预计这无论如何都会受到 I/O 速度的限制,但如果它真的很重要,你就必须计时。
猜你喜欢
  • 2015-01-17
  • 2021-09-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多