【问题标题】:How do I iterate through all files inside a given directory and create folders and move the file?如何遍历给定目录中的所有文件并创建文件夹并移动文件?
【发布时间】:2019-05-14 17:05:44
【问题描述】:

我有一个包含大约 500 个文件的文件夹。

我在根据这 500 个文件名创建文件夹时遇到问题。例如,如果我首先有 A.txt、B.txt 等文件,我想创建名为“A”和“B”的文件夹,然后将“A.txt”文件推送到名为“A”和“ B.txt' 命名文件到我刚刚创建的名为“B”的文件夹中。所以基本上两个任务首先是根据文件名创建文件夹,然后将相应的文件推送到命名文件夹中。

但是,我被困在两个地方,首先,文件夹名称被创建为“A.txt”、“B.txt”等,而不是“A”或“B”,因为我正在使用文件名本身,其次是将文件放入相应的文件夹中。

我试过下面的代码:

       import os, shutil, glob
       import pandas as pd

       def i2f(directory):
       for filename in os.listdir(directory):
           foldername = filename
           folder_loc = "all_files\user\txt-images"
           crfolder(os.path.join(folder_loc, foldername))
           '''
           crfolder is function that creates a folder
           '''
           src_dir = r"all_files\user\txt-images\src_folder" 
           dstn_dir = r"all_files\user\txt-images\trgt_folder" 
           for file in glob.glob("\\*.txt"):
           re.compile(r"[^_.A-Z]")
           shutil.copy2(file, dstn_dir)

       def crfolder():
           import os
           try:
              if not os.path.exists(folder_loc):
                 os.makedirs(folder_loc)
           except OSError:
              print ('''Can't create directory! ''' +  folder_loc)

感谢任何帮助告诉我我哪里弄错了。

【问题讨论】:

标签: python


【解决方案1】:

让事情变得简单:

import os, shutil
parent_folder = 'myfolder'

# get files only not folders
files = [name for name in os.listdir(parent_folder) if os.path.isfile(os.path.join(parent_folder, name))]

for f_name in files:
    file = os.path.join(parent_folder, f_name)  # full path

    folder_name = f_name.split('.')[0]  # remove file extension
    folder = os.path.join(parent_folder, folder_name)  # full path

    if not os.path.exists(folder):  # make folder if not existed before
        os.mkdir(folder)

    shutil.move(file, os.path.join(folder, f_name))  # move file

【讨论】:

  • 如果文件名包含多个句点,您的代码将无法正常工作。前任。 hello.world.txtelshhat.goog.png 会在您的代码中创建文件夹 helloelshhat,这是不正确的。而是使用os.path.splitext(x)[0] ,因为它会给你实际的文件名,没有扩展名。
【解决方案2】:

试试这个:

import os
import shutil

path = r"C:\Users\vasudeos\OneDrive\Desktop\newfolder"

for x in os.listdir(path):

    file = os.path.join(path, x)

    if not os.path.isdir(file):
        folder_name = os.path.join(path, os.path.splitext(x)[0])

        if not os.path.exists(folder_name):
            os.mkdir(folder_name)

        shutil.move(file, folder_name)

【讨论】:

    猜你喜欢
    • 2017-06-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-14
    相关资源
    最近更新 更多