0
1

More than 3 years have passed since last update.

Pythonでローカルファイルを扱うときはpathlibを使うとイイ

Posted at

Pythonでローカルのテキストや画像を開く方法の備忘録です。

環境

  • Mac Catalina
  • Anaconda
  • Jupyter Note

pathlibのPathを使う

/¥の違いを吸収してパスを生成してくれるようです。

ローカルのテキストを開く

from pathlib import Path
file = Path('/Users/ユーザ名/Documents/dev/python-benkyo/txt')
file = file / 'test.txt'        #「パス / ファイル名」でパスにファイル名を追加できる
with open(file) as f:
    print(f.readline())

ディレクトリパスにファイル名を追加するときも、パス「/」ファイル名で追加できるので便利そうです。

結果

テストファイルの中身

UFT-8の文字コードなら日本語も問題なさそうです。

ローカルのJPG画像を開く

画像はPILのImageを使用します。

from pathlib import Path
from PIL import Image
file = Path('/Users/ユーザ名/Documents/dev/python-benkyo/img')
file = file / '001.jpg'
im = Image.open(file)
im.show()

im.show()でMacのプレビューが立ち上がり、画像が表示されます。

以上です。

0
1
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
1