简体   繁体   English

如何在Python中抓取文件名并为每个文件名创建目录?

[英]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 : 无需使用dirname ,您应该写入destination ,而不是同一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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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