9cubed
ブログ | Tailwind | Vite | Python | MariaDB | Node.js | Linux | PowerShell | Docker | Git | その他 | 将棋ウォーズ | 歌の練習
< 前の記事

Python - テキストファイルの入出力(書込、読込)

次の記事 >

Python - numpy - ndarray

Python

Python - バイナリーファイルの入出力(書込、読込)

公開日:2019-04-17
更新日:2019-05-29

1. 概要

バイナリーファイルの入出力(書込、読込)を行います。

関連記事
バイナリーの操作(bytes)
文字列と文字コードの変換(エンコード、デコード)

2. バイナリーファイルの入出力

バイナリーファイルを扱う場合は、mode に「b」をつけます。
write() の引数、read() の戻り値は、bytes になります。

#ファイル書き込み
f = open("test.txt", mode = "wb")
f.write(b"ABCDEFG")
f.close

#ファイル読み書き
with open("test.txt", mode = "rb") as f:
	data = f.read()

#結果表示
for b in data:
	print(b, end=" ")

print("")

for b in data:
	print(chr(b), end=" ")
65 66 67 68 69 70 71
A B C D E F G

3. テキストファイルをバイナリで読み込んで復元

テキスト形式で書き込んだファイルを、バイナリー形式で読み込んで、元の文字列に復元します。

#テキストファイル書き込み
with open("test.txt", mode = "w", encoding="utf-8") as f:
	f.write("あいうえお")
	f.close

#バイナリーファイル読み込み
with open("test.txt", mode = "rb") as f:
	data = f.read()

s = data.decode("utf-8")
print(s)

あいうえお

< 前の記事

Python - テキストファイルの入出力(書込、読込)

次の記事 >

Python - numpy - ndarray

YouTube X

新着一覧

  • テーブル結合(CROSS JOIN、INNER JOIN、LEFT JOIN)MariaDB
  • 楽観ロック・悲観ロックMariaDB
  • カレントリードMariaDB
  • インデックスMariaDB
  • 論理削除(ソフトデリート)MariaDB
  • awk(オーク)の使い方についてLinux
  • NOT NULL 制約と NULL を許容した時の動作MariaDB
  • 外部キー制約MariaDB
  • MySQL と MariaDB の関係MariaDB
  • Docker で PostgreSQL のコンテナの使用Linux

アーカイブ

  • 2026/01
  • 2025/12
  • 2025/11
  • 2025/10
  • 2025/09
  • 2025/08
  • /00

以前のカテゴリー一覧

  • CakePHP3
  • CentOS7
  • HTML・CSS・JavaScript
  • Haskell
  • JavaScript
  • Kotlin
  • Laravel5
  • PHP
  • Python
  • Ruby
  • RubyOnRails5
  • TypeScript
  • Vue.js
  • Webサーバ講座
  • Webプログラミング講座
  • jQuery
  • linux
  • パソコン講座
  • ブログ
  • プログラミング講座
  • メモ帳作成講座
  • 数学

Copyright © 9cubed. All Rights Reserved.

プライバシーポリシー 利用規約
▲