0
0

Pythonで「ファイルやディレクトリの存在を確認する(pathlibモジュール)」の動作を確認してみた

Posted at

概要

Pythonで「ファイルやディレクトリの存在を確認する(pathlibモジュール)」の動作を確認してみました。
以下のページを参考にしました。

実装

以下のファイルを作成しました。

sample.py
import pathlib

path1 = './test/address.txt'
p1 = pathlib.Path(path1)
if p1.exists() :
  print(path1 + 'は存在します')
else :
  print(path1 + 'は存在しません')

path2 = './test/user.txt'
p2 = pathlib.Path(path2)
if p2.exists() :
  print(path2 + 'は存在します')
else :
  print(path2 + 'は存在しません')

path3 = './test/img'
p3 = pathlib.Path(path3)
if p3.exists() :
  print(path3 + 'は存在します')
else :
  print(path3 + 'は存在しません')

以下のコマンドを実行しました。

$ mkdir test
$ mkdir test/doc
$ mkdir test/img
$ touch test/address.txt
$ touch test/name.txt
$ python3 sample.py 
./test/address.txtは存在します
./test/user.txtは存在しません
./test/imgは存在します

まとめ

何かの役に立てばと。

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