Pythonを用いて、ダウンロードしたファイルを任意のディレクトリに移動する方法を紹介します。
ファイル移動の実装方法
下記の流れでダウンロードファイルの移動を行います。
- ダウンロード先ディレクトリのファイルリストを取得
- 最新のファイルを取得
- 最新のファイルを移動先ディレクトリに移動
import shutil
def run_script():
-----ダウンロード処理-----
# ダウンロードしたファイルを移動
download_dir = "ダウンロード先"
target_dir = "移動先"
# ダウンロードフォルダ内の最新ファイルを取得
list_of_files = os.listdir(download_dir)
full_paths = [os.path.join(download_dir, f) for f in list_of_files]
latest_file = max(full_paths, key=os.path.getctime) # 作成日時が最新のファイルを取得
# 移動先フォルダが存在しない場合は作成
os.makedirs(target_dir, exist_ok=True)
# ファイルを移動
shutil.move(latest_file, os.path.join(target_dir, os.path.basename(latest_file)))