将具有特定名称的文件放入具有其名称的文件夹

时间:2018-09-27 10:41:33

标签: python

我在一个名为output的文件夹中有几个文件。

文件为a.shp, a.dbf, a.shx, b.shp, b.dbf, b.shx等。 如何在output内然后在'exports'内创建一个文件夹'exports',一个叫做a的文件夹,然后自动放置在a.shp, etc里,依此类推,以其他文件夹中的文件?

示例:

from glob import glob
folder = C:/Users/user/Desktop/programs/merge/output
for i in glob(folder + '/*'):
    if ('a') in i:
         print(i)

给予

C:/Users/user/Desktop/programs/merge/output\a.dbf
C:/Users/user/Desktop/programs/merge/output\a.shp
C:/Users/user/Desktop/programs/merge/output\a.shx

我尝试过的事情:

from glob import glob
folder = C:/Users/user/Desktop/programs/merge/output
os.mkdir(folder +'/'+ 'exports' )
for i in glob(folder + '/*'):
    if ('a') in i:
        os.mkdir(folder +'/'+ 'exports' + '/' + i.split("\\")[-1]) 
# Creates a folder for each extension as well which is not needed. I want only by the name.
# and somehow all these files have to be moved to these folders

2 个答案:

答案 0 :(得分:1)

下订单,否则将导致MAD:

from shutil import copyfile


folder = C:/Users/user/Desktop/programs/merge/output
export_folder = os.path.join(folder, 'exports')
os.mkdir(export_folder)
for file in os.listdir(folder):
    filename = os.path.basename(file)
    file_without_extension = filename.split('.')[0] #ASSUMING THEY ONLY HAVE ONE DOT
    output_dir = os.path.join(export_folder, file_without_extension)
    os.mkdir(output_dir)
    copyfile(os.path.join(folder, filename), os.path.join(output_dir, filename))

答案 1 :(得分:0)

来自Rakesh的回答。通过编辑使其生效。除了权限错误外,他的回答还在“ exports”文件夹中创建了一个“ exports”文件夹。

if not os.path.isdir(os.path.join(folder, 'exports')):     #Check if 'exports' folder exists.
    os.mkdir(os.path.join(folder, 'exports'))              #Else create folder.

for file in os.listdir(folder): 
    if '.' in file:           #this addition made it work.
        filename = file.split(".")[0]         
        dest = os.path.join(folder, 'exports', filename)       
        if not os.path.isdir(dest):
            os.mkdir(dest)
        copyfile(os.path.join(folder, file), os.path.join(dest, file))   

对于原始张贴者:如果您可以解释为什么它使这些文件夹像这样“导出”,并用修复该问题的编辑来编辑您的答案,我将接受您的并将其删除。 谢谢你的主意。