スポンサーリンク

Chainer用の画像処理メモ(3)pythonでのファイルの読み書き”import os”

機械学習で、Chainer用の画像→ndarray変換を行うために、pythonの勉強をしている。

http://twosquirrel.mints.ne.jp/?p=20084

前回は、リスト、タプル、for文、について、以下の本で勉強してみた。

今回は、●8章 ファイルの読み書き(import os で使用するもの) の一部を写経してみたい。

(環境)
Panasonic CF-RZ4
Windows 8.1 Pro
Anaconda 4.4.0
Python 3.5
Chainer 2.0
OpenCV3

(1)Windowsのバックスラッシュ(“\”)、MacやLinuxのスラッシュ(“/”)

# 8章 ファイルの読み書き
import os
# 以下のコマンドでは、
# Windowsでは、’usr\bin\spam’という文字列を返す
# MacやLinuxでは、’usr/bin/spam’という文字列を返す
os.path.join(‘usr’, ‘bin’, ‘spam’)

image

import os
my_files = [‘account.txt’, ‘details.csv’, ‘invite.docx’]
for filename in my_files:
print(os.path.join(‘C:/Users/asweigart’, filename))
# 上記を、    join(‘C:\Users\asweigart’, filename))
# とするとSyntax Error(unicode error)… となってしまった

(2)カレントディレクトリ

# カレントディレクトリ
import os
os.getcwd()

image

import os
os.chdir(‘C:/Windows/System32’)
os.getcwd()

(3)os.makedirs()関数を用いて、新しいフォルダを作る

# os.makedirs()関数を用いて、新しいフォルダを作る
# 中間フォルダも作成してくれる

import os
os.makedirs(‘./delicious/walnut/waffles’)

image

image

ちゃんと、wafflesフォルダと、その中間フォルダが作成されている。

2回目以降は、以下のようなエラーとなる。

image

(参考)

NumPy 配列の基礎
http://www.kamishima.net/mlmpyja/nbayes1/ndarray.html

(4)絶対パスと相対パス

import os
os.path.abspath(‘.’)

image

(5)Pythonでファイルを読み書きする3つのステップ

1. open()関数を呼び出し、Fileオブジェクトを取得する。
2. Fileオブジェクトのread()やwrite()メソッドを呼び出して読み書きする。
3. Fileオブジェクトのclose()メソッドを呼び出してファイルを閉じる。

# open()関数を用いてファイルを開く

# hello.txt という名前のファイルを作成し、中身をHello world! と入力して保存。

image

# open()関数を用いてファイルを開く
# hello.txt という名前のファイルを作成し、中身を
# Hello world! と入力して保存。
# hello.txtを開く
hello_file = open(‘C:/py/chainer2/python_test/hello.txt’)
# hello_file = open(‘C:/py/chainer2/python_test/hello.txt’, ‘r’)  でもよい。
# 読み書きできるようにopenする場合は、
# hello_file = open(‘C:/py/chainer2/python_test/hello.txt’, ‘w’)
# つまり、書き込みモードは、openの第2引数がw
# ちなみに、追記モードは、openの第2引数がa
# 開いたファイルを読み込む(???)
hello_content = hello_file.read()
hello_content

image

os

ちなみに、

!ls -l

のように、! をつけると、コマンドプロンプトでの操作ができるらしい。

image

次は、画像の操作(主に、PIL、pillow)について写経してみたい。

その次は、最難関のnumpy配列について勉強してみたい

(参考)

pythonでフォルダ内のファイル一覧をパス無しで取得する
https://qiita.com/CORDEA/items/ee44799e5d029ce3aaac

スポンサーリンク