在unix系统上用python排序文件 [英] sorting file in place with Python on unix system

查看:210
本文介绍了在unix系统上用python排序文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用自定义的unix命令从Python中排序文本文件,该命令将文件名作为输入(或从stdin读取)并写入stdout。我想排序 myfile ,并保留排序的版本。从Python做这个临时文件是最好的方法吗?我目前的解决方案是:

$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ =%s.tmp_file%(输入文件)
cmd =mysort%s>%s%(输入文件,tmpfile)
#重命名已​​排序的文件原始排序文件名
os .rename(tmpfile,inputfile)

这是最好的解决方案吗?如果你不想创建临时文件,你可以使用 subprocess code $>

pre $进口系统
进口子进程

fname = sys.argv [1]
proc = subprocess.Popen(['sort',fname],stdout = subprocess.PIPE)
stdout,_ = proc.communicate()
with open fname,'w')作为f:
f.write(stdout)


I'm sorting a text file from Python using a custom unix command that takes a filename as input (or reads from stdin) and writes to stdout. I'd like to sort myfile and keep the sorted version in its place. Is the best way to do this from Python to make a temporary file? My current solution is:

inputfile = "myfile"
# inputfile: filename to be sorted
tmpfile = "%s.tmp_file" %(inputfile)
cmd = "mysort %s > %s" %(inputfile, tmpfile)
# rename sorted file to be originally sorted filename
os.rename(tmpfile, inputfile)

Is this the best solution? thanks.

解决方案

If you don't want to create temporary files, you can use subprocess as in:

import sys
import subprocess

fname = sys.argv[1]
proc = subprocess.Popen(['sort', fname], stdout=subprocess.PIPE)
stdout, _ = proc.communicate()
with open(fname, 'w') as f:
    f.write(stdout)

这篇关于在unix系统上用python排序文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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