LoginSignup
0
0

Pythonで「ディレクトリに含まれるファイルとディレクトリの一覧を取得する」の動作を確認してみた

Posted at

概要

Pythonで「ディレクトリに含まれるファイルとディレクトリの一覧を取得する」の動作を確認してみました。
以下のページを参考にしました。

実装

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

sample1.py
import os

path = './test/'
filelist = os.listdir(path)

for f in filelist:
  print(f)
  print(os.path.join(path, f))
sample2.py
import os

path = './test/'
filelist = os.listdir(path)

for f in filelist:
  if os.path.isfile(os.path.join(path, f)):
    print('[F]:' + f)
  else:
    print('[D]:' + f)
sample3.py
import os

path = './test/'
for i in os.scandir(path):
  if i.is_file():
    print('[F]:' + i.name + ' ' + i.path)
  else:
    print('[D]:' + i.name + ' ' + i.path)

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

$ mkdir test/doc
$ mkdir test/img
$ touch test/address.txt
$ touch test/name.txt
$ python3 sample1.py 
address.txt
./test/address.txt
img
./test/img
name.txt
./test/name.txt
doc
./test/doc
$ python3 sample2.py 
[F]:address.txt
[D]:img
[F]:name.txt
[D]:doc
$ python3 sample3.py 
[F]:address.txt ./test/address.txt
[D]:img ./test/img
[F]:name.txt ./test/name.txt
[D]:doc ./test/doc

まとめ

何かの役に立てばと。

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