0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【os・glob・pathlib】Pythonにおけるファイルのパスの取り扱いまとめ

Posted at

概要

当記事ではPythonの処理の実行を「ディレクトリ単位で行う際」や「ファイル名の法則性に基づいて処理対象を決める際」などに有用なファイルのパスの取り扱い方法について取りまとめました。

ファイルのパスの取り扱い

osモジュール

指定したディレクトリのファイルを取得するにあたっては下記のようにos.listdirなどを用いると良いです。

import os

file_list = os.listdir("test")

print(type(file_list), file_list)

・実行結果

<class 'list'> ['file_name1.txt', 'file_name2.png', 'file_name3.csv' ]

globモジュール

os.listdirではディレクトリ内の全てのファイルのリストを返しますが、特定の拡張子のみを取り出したいなどファイル名に何らかの指定も付与したい場合などもあります。このような際はglobなどを用いると良いです。

import glob

file_list = glob.glob("*.txt")

print(type(file_list), file_list)

・実行結果

<class 'list'> ['file_name1.txt' ]

pathlib

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?