MicroPythonで使うWio Terminal - ファイルの読み書き

MicroPythonで使うWio Terminal - 目次

簡単なファイルの読み書き例

# Wio Terminal io, osのサンプル
# MicroPythonの公式ドキュメントに説明がある
# https://micropython-docs-ja.readthedocs.io/ja/latest/library/io.html
# https://micropython-docs-ja.readthedocs.io/ja/latest/library/os.html
# This code is provided under a CC0 Public Domain License.
# http://creativecommons.org/publicdomain/zero/1.0/
# 2022年6月27日 佐藤恭一 https://kyoutan.jpn.org

import os

f = open("myfile.txt", "w", encoding="utf-8")  # 書き込むファイルを作成する
f.write("1:abcdefg\r\n")  # 何か書き込んでみる
f.write("2:0123456789\r\n")
f.write("3:hijklmn\r\n")
f.write("4:opqrstu\r\n")
f.close()  # ファイルクローズ

print(os.listdir())  # ファイル一覧表示

f = open("myfile.txt", "r", encoding="utf-8")  # 読み取るファイルを開く
print(f.readline())  # 一行読んで表示
f.seek(0)            # ファイル先頭にシーク
print(f.readline())  # 一行ずつ読んで表示
print(f.readline())
print(f.readline())
print(f.readline())
f.close()  # ファイルクローズ

os.remove("myfile.txt")  # ファイル削除
print(os.listdir())  # ファイル一覧表示 "mytext.txt" が消えているのが確認できる

"""
>>> import io,os
>>> help(io)
object <module 'uio'> is of type module
  __name__ -- uio
  open -- <function>
  FileIO -- <class 'FileIO'>
  StringIO -- <class 'StringIO'>
  BytesIO -- <class 'BytesIO'>
>>> help(io.FileIO)
object <class 'FileIO'> is of type type
  read -- <function>
  readinto -- <function>
  readline -- <function>
  readlines -- <function>
  write -- <function>
  flush -- <function>
  close -- <function>
  seek -- <function>
  tell -- <function>
  __del__ -- <function>
  __enter__ -- <function>
  __exit__ -- <function>
>>> help(io.StringIO)myfiletxtobject <class 'StringIO'> is of type type
  read -- <function>
  readinto -- <function>
  readline -- <function>
  write -- <function>
  seek -- <function>
  flush -- <function>
  close -- <function>
  getvalue -- <function>
  __enter__ -- <function>
  __exit__ -- <function>
>>> help(io.BytesIO)
object <class 'BytesIO'> is of type type
  read -- <function>
  readinto -- <function>
  readline -- <function>
  write -- <function>
  seek -- <function>
  flush -- <function>
  close -- <function>
  getvalue -- <function>
  __enter__ -- <function>
  __exit__ -- <function>
>>> help(os)
object <module 'uos'> is of type module
  __name__ -- uos
  uname -- <function>
  chdir -- <function>
  getcwd -- <function>
  ilistdir -- <function>
  listdir -- <function>
  mkdir -- <function>
  remove -- <function>
  rename -- <function>
  rmdir -- <function>
  stat -- <function>
  statvfs -- <function>
  unlink -- <function>
  sync -- <function>
  sep -- /
  mount -- <function>
  umount -- <function>
  VfsFat -- <class 'VfsFat'>
"""

Wio Terminalの内蔵フラッシュメモリ上にファイルシステムが用意されていて、ファイルを読んだり書いたりできます。マイコンではファイルシステムを使うことができないことも多いのですが、ファイルシステムがあるとデータを保存したりできて便利。


このブログの人気の投稿

windowsで「インターネット接続の共有」の設定

月刊 I/O 記事リスト 1976~1989

X68000実機のROMを保存