【问题标题】:How to run unix commands through Python to edit files in place如何通过 Python 运行 unix 命令来就地编辑文件
【发布时间】:2014-02-14 18:28:12
【问题描述】:

我必须打开一个 xml 文件,删除空格(换行符除外),删除与正则表达式匹配的所有行,然后删除与另一个正则表达式匹配的所有行。现在这是使用 3 个单独的临时文件,我知道这是不必要的。

# Trim whitespace from xml
f2 = open(fname + '.xml','r')
f3 = open(fname + 'temp.xml', 'w')
subprocess.call(["tr", "-d", "'\t\r\f'"], stdin=f2, stdout=f3)
f2.flush()
f3.flush()

# Remove the page numbers from the file                         
f4 = open(fname + 'temp2.xml', 'w')
subprocess.call(["sed",
"/<attr key=\"phc.line_number\"><integer>[0-9]*<\/integer><\/attr>/d",
                                    fname + 'temp.xml'], stdout=f4)
f4.flush()

# Remove references to filename from the file
--not implemented--

有没有办法让我用一个文件完成所有这些操作?

【问题讨论】:

    标签: python file unix subprocess in-place


    【解决方案1】:
    $ sed -i -e 's/[ \r\t\f]//g' -e /pattern1/d -e /pattern2/d x.xml
    

    注意多个-e 参数。 -i 将结果留在x.xml

    【讨论】:

      猜你喜欢
      • 2013-03-24
      • 1970-01-01
      • 2013-11-20
      • 1970-01-01
      • 1970-01-01
      • 2011-08-29
      • 1970-01-01
      • 2010-09-13
      • 1970-01-01
      相关资源
      最近更新 更多