LoginSignup
3
2

More than 3 years have passed since last update.

[Python] Pythonでフォルダ内のファイルを取得

Last updated at Posted at 2020-03-08

フォルダ内のXMLを取得してParseする必要が生じたので、ファイルパス取得を試みました。

ライブラリ

globというライブラリをインポートします。
osはファイル名取得に必要なライブラリです。

import glob
import os

フォルダ指定

*(アスタリスク)でフォルダ内の全てのファイルを指定します。

file = glob.glob("C:/Users/user/*")

今回はXMLを取得するのでこんな感じでファイルパスが取得できます。

print(file)
['C:/Users/user/AAAAAA.xml', 'C:/Users/user/BBBBBB.xml']

ファイル名取得

csvに書き出しする際にユニークなファイル名を利用したいので、ついでにファイル名も取得しておきます。
ファイルパス一覧からまずAAAAAA.xmlを取得します。
その後ファイル名を取得するためにos.path.splitを使用しました。

file_A = file[0] //一番上のファイルパスを取得
filename = os.path.split(file_A)[1]

これでファイル名が取得できました。

print(filename)
AAAAAA.xml

フォルダには時間的にイレギュラーかつXMLファイル数も予測できないため、実際にはループ処理する必要があります。
ループに関しては次回投稿しようと思います。

3
2
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
3
2