diadia

興味があることをやってみる。自分のメモを残しておきます。

ディレクトリの指定

現状のパス問題点

ディレクトリの操作、ファイルの操作に関して個別具体的なパスで記述している。そのためスクリプトを移動してしまうと途端に関連するスクリプトにファイルを読み込めなくなってしまう。具体性を排除して、汎用的なファイル操作ができるようにしたい。

操作確認

C:\Users\user\program\dir_test.pyで試してみる。

test1

print(os.getcwd())

結果

C:\Users\user\program

test2

print(__name__)

結果

__main__

test3

print(__file__)

結果

dir_test.py

この__file__はモジュールファイルのパスを文字列として保存してあるらしい。byみんなのpython

test4

print(os.path.abspath(__file__))

結果

C:\Users\user\program\dir_test.py

test5

print(os.path.dirname(os.path.abspath(__file__)))

結果

C:\Users\user\program

os.path.dirname(os.path.abspath(__file__))とos.getcwd()の結果が同じだった。でこれはカレントディレクトリを示す。

カレントディレクトリに新たにディレクトリを作る場合

os.mkdir("dir1")

カレントディレクトリにdir1を作成することができた。mkdir(パス)なのでmkdir(フルパス)にするには以下のようにする。

os.mkdir(os.path.join(os.path.dirname(os.path.abspath(__file__)),"dir2"))

新たに作ったディレクトリに画像ファイルを保存する

まず新たに作ったディレクトリのパスを取得する。それにつなげてurllib.request.retrieve()を用いる。
新たに作ったディレクトリのパスは以下のように書く。

os.path.dirname(os.path.abspath(__file__))

画像urlは以下のものにする。https://www.google.co.jp/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png。だから画像のダウンロード自体は以下になる。

import urllib.request
url ="https://www.google.co.jp/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png"
save_name = "image.png"
urllib.request.retrieve(url,save_name)

これらを合わせるとこうなる。

import urllib.request
url ="https://www.google.co.jp/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png"
save_name = "image.png"
save_name = os.path.join(os.path.dirname(os.path.abspath(__file__)),"dir2",save_name)
urllib.request.retrieve(url,save_name)

指定のディレクトリの画像ファイルすべて削除する

指定のディレクトリ今回は"image"のファイルすべてを削除する

for t in os.listdir("image"):
    file = os.path.join(os.path.dirname(os.path.abspath(__file__)),"image",t)
    os.remove(file)

ちなみに以下の方法だと正確にフルパスを検出できずに、削除する事ができなかった。

for t in os.listdir("image"):
    print(os.path.abspath(t))
    os.remove(os.path.abspath(t))

関連メモ

ディレクトリ、ファイルの削除