LoginSignup
0
3

More than 3 years have passed since last update.

ファイル名一覧をテキスト(.txt)ファイルに書き込む【Python】

Last updated at Posted at 2020-10-09

機械学習のデータセットのためのファイル名一覧などに。
スクリーンショット 2020-10-09 12.20.05.png


import os

path = "./datasets/train" # ファイル名一覧を取得したいディレクトリのパス
text_file = open("./datasets/train.txt", "w") # 書き込み先のテキストファイルを作る

files = os.listdir(path) # ファイル名一覧を取得

for f in files:
  basename_without_ext,ext = os.path.splitext(os.path.basename(f)) # 拡張子抜きのファイル名を取得
  text_file.write(basename_without_ext + "\n") # テキストファイルに書き込む

text_file.close() # テキストファイルを保存

image0
image1
image2
image3


という感じで書き込まれます。
拡張子も書き込みたい場合は、


 # basename_without_ext,ext = os.path.splitext(os.path.basename(f)) # 拡張子抜きのファイル名を取得
basename = os.path.basename(f) # 拡張子ありのファイル名を取得

image0.jpg
image1.jpg
image2.jpg
image3.jpg


🐣


お仕事のご相談こちらまで
rockyshikoku@gmail.com

Core MLを使ったアプリを作っています。
機械学習関連の情報を発信しています。

Twitter
Medium

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