简体   繁体   中英

Have to run glob.glob twice to work (Python3)

I am trying to grab all of the mp3 files in my Downloads directory (after procedurally downloading them) and move them to a new file. However, anytime I try to use glob to grab a list of the available .mp3 files, I have to glob twice for it to work properly (the first time it is running it returns an empty list). Does anyone know what I am doing wrong here?

import glob
import os
import shutil

newpath = r'localpath/MP3s' 
if not os.path.exists(newpath):
    os.makedirs(newpath)

list_of_files = glob.glob('localpath/Downloads/*.mp3')

for i in list_of_files:
    shutil.move(i, newpath)

This turned out to be a timing issue. The files I was trying to access were still in the process of downloading, with is why the glob was returning empty. I inserted a time.sleep(5) before the glob, and it is now running smoothly.

May I suggest an alternate approach

from pathlib import Path
from shutil import move

music = Path("./soundtrack")
# you can include absolute paths  too...
newMusic = Path("./newsoundtrack")

# makes new folder specified in newMusic
newMusic.mkdir(exist_ok=True)

# will select all
list_of_files = music.glob("*")
# u want to select only mp3's do:
# list_of_files = music.glob("*.mp3")

for file in list_of_files:
    move(str(file), str(newMusic))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM