简体   繁体   中英

How can I scrape file names and create directories for each filename in Python?

I'm trying to scrape filenames inside a folder and then make directories for each filename inside another folder. This is what I've got so far but when I run it, it doesn't create the new folders in the destination folder. When I run it in the terminal it doesn't return any errors.

import os
import shutil

folder = "/home/ro/Downloads/uglybettyfanfiction.net/"
destination = "/home/ro/A Python Scripts/dest_test/"

# get each files path name

def ensure_dir(f):
    d = os.path.dirname(f)
    if not os.path.exists(d):
        os.makedirs(d)

for files in os.listdir(folder):
    new_path = folder + files
    ensure_dir(new_path)

You've got a few mistakes. No need to use dirname and you should write to your destination , not the same folder :

def ensure_dir(f):
    if not os.path.exists(f):
        os.mkdir(f)

for files in os.listdir(folder):
    new_path = destination + files
    ensure_dir(new_path)

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