LoginSignup
1
0

More than 3 years have passed since last update.

製薬企業研究者がPythonにおけるファイル走査についてまとめてみた

Posted at

はじめに

ここでは、Pythonを用いたファイル走査の方法として、osモジュールとpathlibモジュールの利用方法を紹介します。

osモジュール

osモジュールは、ファイルやディレクトリを扱う上でベーシックなモジュールです。
よく使うメソッドなどは以下になります。

import os


directory = 'ディレクトリー名'
file = 'ファイル名'

file_path = os.path.join(directory, file)
print(file_path) # ディレクトリ名/ファイル名
print(os.path.isfile(file_path)) # True
print(os.path.isdir(file_path)) # False
print(os.path.isdir(directory)) # True
print(os.path.exists(file_path)) # True

entry_list = []
for entry in os.listdir(directory):
    entry_list.append(entry)
print(directory_list)

directory_list = []
file_list = []
path_list = []
for root, dirs, files in os.walk(directory):
    for drc in dirs:
        directory_list.append(drc)
    for file in files:
        file_list.append(file)
        file_path.append(os.path.join(root, file))
print(directory_list)
print(file_list)
print(path_list)

pathlibモジュール

Python3.4以降はpathlibモジュールを利用することができます。

from pathlib import Path


p_dir = Path('ディレクトリ名')
p_file = Path('ファイル名')

p_path = p_dir / p_file
p_path.mkdir(parents=True, exist_ok=True)
print(p_path)

print(p_path.parts)
print(p_path.parent)
print(p_path.name)
print(p_path.stem)
print(p_path.suffix)

print(p_path.is_file()) # True
print(p_path.is_dir()) # False
print(p_dir.is_dir()) # True
print(p_path.exists()) # True

p_path.rmdir()
print(p_path.exists()) # False

まとめ

ここでは、osモジュールとpathlibモジュールについて解説しました。
まだ説明不足なところもあるので、後日追記予定です。

参考資料・リンク

プログラミング言語Pythonとは?AIや機械学習に使える?

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