LoginSignup
0
0

More than 3 years have passed since last update.

Test&Debug Tips:Pythonで,指定したサイズのファイルを作る

Last updated at Posted at 2021-01-10

はじめに

テストやデバッグに使えそうな小技です。
テスト用に、大きいランダムな内容のファイルを作りたい事がありませんか?。しかも即席で。

コマンドライン1行で"即席"で巨大なファイルを作る

1024バイトのファイルを作る

実行例(1024バイトのファイル作成)
C:\>python -c "import sys; import numpy; sys.stdout.buffer.write(numpy.random.bytes(1024));" > 1024.bin

1MBのファイルを作る

実行例(1MB/1,048,576バイトのファイル作成)
C:\>python -c "import sys; import numpy; sys.stdout.buffer.write(numpy.random.bytes(1048576));" > 1048576.bin

1GBのファイルを作る

実行例(1MB/1,073,741,824バイトのファイル作成)
python -c "import sys; import numpy; sys.stdout.buffer.write(numpy.random.bytes(1073741824));" > 1073741824.bin

Corei7-5500U-2.4GHz/SSD-DISKで1GBのファイルを作成するのに1分くらいかかりました。
(ゼロ埋めのファイルでよければfsutilをどうぞ。一瞬で終わります)

結果を見る

実行結果
C:\work>dir
2021/01/11  10:00             1,024 1024.bin
2021/01/11  10:08         1,048,576 1048576.bin
2021/01/12  19:28     1,073,741,824 1073741824.bin

まとめ

コマンドラインのみで即席で実現する方法を掲載してみました。
忙しい時の助けになれば幸いです。

おまけ

sys.stdout.write()だとエラーになる

エラーになる実行例

>>> sys.stdout.write(numpy.random.bytes(1024))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: write() argument must be str, not bytes

出力しようとするとエラーになりました。バイトは駄目とのこと。
numpy.random.bytesは「b'\xe5'」のようなstring型で返すから大丈夫だと思ったのですが。。

sys.stdoutの型は?

C:\>python
>>> import sys;
>>> print(type(sys.stdout));
<class '_io.TextIOWrapper'>

sys.stdoutの型は'_io.TextIOWrapper'です。

class '_io.TextIOWrapper'とは?

──────────────────────────
class '_io.TextIOWrapper'
A buffered text stream providing higher-level access to a BufferedIOBase buffered binary stream.
It inherits TextIOBase.(TextIOBaseを継承する
──────────────────────────
'_io.TextIOWrapper'はテキスト処理用のクラスでした。しかたないのでバイト型のインタフェースを探します
'TextIOBase'を継承するとあります。

class io.TextIOBaseとは?

──────────────────────────
class io.TextIOBase
Base class for text streams. This class provides a character and line based interface to stream I/O. It inherits IOBase. There is no public constructor.
──────────────────────────
このクラスにはバイナリIFにアクセスするbufferというメンバがいました。

io.TextIOBase.buffer(sys.stdout.buffer)とは?

──────────────────────────
buffer
TextIOBase が扱う根底のバイナリバッファ (BufferedIOBase インスタンス) です。
──────────────────────────
バイナリ出力にはbufferを使えば良いようです。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0