【问题标题】:How to send part of the output of a Python script to a text file?如何将 Python 脚本的部分输出发送到文本文件?
【发布时间】:2011-11-22 05:23:30
【问题描述】:

我只想将 script.py 的部分输出保存到另一个文件夹中的文件中。

script.py 打印出文件名及其大小的列表,例如

file_asfs.txt- 2KB
file_jsdfhkjh.doc- 17KB
....

如果我只想将正好 2KB 的文件名列表保存在文本文件 /temp/filelist 中,我该怎么做?

【问题讨论】:

  • 在 unix 中,您可以使用sedawkgrep 等从输出中提取您想要的部分。

标签: python save text-files


【解决方案1】:
script.py | grep "\\b2KB$" > output.txt

【讨论】:

  • 我只想保存文件名,而不是包括名称和大小在内的整个字符串...
  • 我知道了,使用 grep 和 awk 的组合
【解决方案2】:

您可以创建一个程序来过滤它: 过滤器.py:

import sys
for line in sys.stdin:
        line=line.strip()
        if line.endswith("- 2KB"):
                print line

然后去

python script.py | python filter.py > /temp/filelist.txt

【讨论】:

    猜你喜欢
    • 2022-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-11
    相关资源
    最近更新 更多