在Python中重现Unix cat命令 [英] Reproduce the Unix cat command in Python

查看:90
本文介绍了在Python中重现Unix cat命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am currently reproducing the following Unix command:

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

在Python中具有以下内容:

in Python with the following:

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

可以,但是有成为更好的方法。有什么建议吗?

which works, but there has to be a better way. Any suggestions?

编辑(2016):

这个问题在四年后开始引起人们的关注。我在更长的Jupyter笔记本电脑这里写了一些想法

This question has started getting attention again after four years. I wrote up some thoughts in a longer Jupyter Notebook here.

问题的症结在于,我的问题与 readlines 的行为(我个人没想到)有关。可以更好地提出我想要的答案,而使用 read()。splitlines()可以更好地回答该问题。

The crux of the issue is that my question was pertaining to the (unexpected by me) behavior of readlines. The answer I was aiming toward could have been better asked, and that question would have been better answered with read().splitlines().

推荐答案

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

The easiest way might be simply to forget about the lines, and just read in the entire file, then write it to the output:

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())

如评论中指出,如果两个输入都很大(因为它首先将整个文件复制到内存中)。如果这可能是一个问题,则以下操作也将同样有效(通过分块复制输入文件):

As pointed out in a comment, this can cause high memory usage if either of the inputs is large (as it copies the entire file into memory first). If this might be an issue, the following will work just as well (by copying the input files in chunks):

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)

这篇关于在Python中重现Unix cat命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆