Help us understand the problem. What is going on with this article?

pythonで巨大なファイルをソートする

More than 3 years have passed since last update.

subprocess.Popenの挙動の勉強になったので、忘れないようにメモ

pythonで巨大なファイルを扱うときは、全てをメモリに載せないよう、イテレータを使っての逐次処理を非常に頻繁に行う。
が、sorted()関数は巨大なファイルに対しては使えない。これはイテレータをリストに変換してから処理を行うため。

巨大なファイルをソートしたいときはUnixシステム側のsortを使う

import subprocess
def sorted_file_generator(filename):
    proc = subprocess.Popen(['sort', filename], stdout=subprocess.PIPE)
    while True:    # while を使って1行ずつ受け取る
        line = proc.stdout.readline()
        if line:
            yield line.decode('utf-8').strip()    # 返り値はバイトコードなのでデコードする
        else:
            break

この例はpython3です。
2の場合は、バイトの取り扱いが違うはず

joemphilips
ex-bioinformatician, now blockchain developer. TypeScript, rust, python
http://joemphilips.com
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした