10

我目前正在复制以下 Unix 命令:

cat command.info fort.13 > command.fort.13

在 Python 中使用以下内容:

with open('command.fort.13', 'w') as outFile:
  with open('fort.13', 'r') as fort13, open('command.info', 'r') as com:
    for line in com.read().split('\n'):
      if line.strip() != '':
        print >>outFile, line
    for line in fort13.read().split('\n'):
      if line.strip() != '':
        print >>outFile, line

这行得通,但必须有更好的方法。有什么建议么?

编辑(2016):

时隔四年,这个问题再次受到关注。我在这里用更长的 Jupyter Notebook 写下了一些想法。

问题的症结在于我的问题与readlines. 我想要的答案本来可以更好地提出,而这个问题本来可以更好地回答read().splitlines()

4

6 回答 6

15

最简单的方法可能是简单地忘记这些行,只需读入整个文件,然后将其写入输出:

with open('command.fort.13', 'wb') as outFile:
    with open('command.info', 'rb') as com, open('fort.13', 'rb') as fort13:
        outFile.write(com.read())
        outFile.write(fort13.read())

正如评论中所指出的,如果任何一个输入很大(因为它首先将整个文件复制到内存中),这可能会导致高内存使用。如果这可能是一个问题,以下内容也可以正常工作(通过以块的形式复制输入文件):

import shutil
with open('command.fort.13', 'wb') as outFile:
    with open('command.info', 'rb') as com, open('fort.13', 'rb') as fort13:
        shutil.copyfileobj(com, outFile)
        shutil.copyfileobj(fort13, outFile)
于 2012-07-18T01:22:00.883 回答
8
def cat(outfilename, *infilenames):
    with open(outfilename, 'w') as outfile:
        for infilename in infilenames:
            with open(infilename) as infile:
                for line in infile:
                    if line.strip():
                        outfile.write(line)

cat('command.fort.13', 'fort.13', 'command.info')
于 2012-07-18T01:20:37.203 回答
6
#!/usr/bin/env python
import fileinput

for line in fileinput.input():
    print line,

用法:

$ python cat.py command.info fort.13 > command.fort.13

或者允许任意大行:

#!/usr/bin/env python
import sys
from shutil import copyfileobj as copy

for filename in sys.argv[1:] or ["-"]:
    if filename == "-":
        copy(sys.stdin, sys.stdout)
    else:
        with open(filename, 'rb') as file:
            copy(file, sys.stdout)

用法是一样的。

或者在 Python 3.3 上使用os.sendfile()

#!/usr/bin/env python3.3
import os
import sys

output_fd = sys.stdout.buffer.fileno()
for filename in sys.argv[1:]:
    with open(filename, 'rb') as file:
        while os.sendfile(output_fd, file.fileno(), None, 1 << 30) != 0:
            pass

上面的sendfile()调用是为 Linux > 2.6.33 编写的。原则上,sendfile()它比其他方法使用的读/写组合更有效。

于 2013-01-19T05:35:57.490 回答
1

遍历文件会产生行。

for line in infile:
  outfile.write(line)
于 2012-07-18T01:16:32.953 回答
1

您可以通过以下几种方式进行简化:

with open('command.fort.13', 'w') as outFile:
  with open('fort.13', 'r') as fort13, open('command.info', 'r') as com:
    for line in com:
      if line.strip():
        print >>outFile, line
    for line in fort13:
      if line.strip():
        print >>outFile, line

更重要的是,shutil模块具有 copyfileobj 功能:

with open('command.fort.13', 'w') as outFile:
  with open('fort.13', 'r') as fort13:
    shutil.copyfileobj(com, outFile)
  with open('command.info', 'r') as com:
    shutil.copyfileobj(fort13, outFile)

这不会跳过空白行,但 cat 也不会这样做,所以我不确定你是否真的想要。

于 2012-07-18T01:23:23.487 回答
1

对于这样的事情,列表推导很棒:

with open('command.fort.13', 'w') as output:
  for f in ['fort.13', 'command.info']:
    output.write(''.join([line for line in open(f).readlines() if line.strip()]))
于 2012-11-22T00:02:20.447 回答