繁体   English   中英

组织文件并将其复制到新文件夹

[英]Organizing and copying files to new folders

我正在尝试整理一些数据,然后再处理它。

我所拥有的是原始tiff文件的文件夹(它们是来自无人机传感器的光栅带)。 文件结构示例

我想将这些文件移动到新的单个文件夹中。 例如,IMG_001_1,IMG_001_2,IMG_001_3,IMG_001_4和IMG_001_5都移到了名为IMG_001的新文件夹中。 我可以更改文件的命名结构,以使代码更简单。

另一个问题是文件夹中缺少一些图像。 当前文件为IMG0016-IMG0054(无IMG0055),IMG0056-IMG0086(无IMG0087)和IMG0087-IMG0161。 这就是为什么我认为从1-143重命名新的图像文件夹会更简单。

我的主要问题实际上是将文件移到新文件夹中-创建文件夹非常简单。

玩了一点,这个脚本就出来了,它应该做你想要的:

import os
import shutil
import re

UNORG = "C:\\Users\joshuarb\Desktop\Unorganized_Images\\"
ORG = "C:\\Users\joshuarb\Desktop\Organized_Images\\"


def main():
    file_names = [os.path.join(UNORG, i) for i in get_files_of(UNORG)]
    for count in range(0, 143):
        current_dir = "{}IMG_{:04d}".format(ORG, count)
        os.makedirs(current_dir)
        move_files = get_files_to_move(file_names, count)
        print move_files
        for i in move_files:
            shutil.move(i, os.path.join(current_dir, os.path.basename(i)))


def get_files_to_move(file_names, count):
    return [i for i in file_names if re.match('.*IMG{}_.*'.format(count), i)]


def get_files_of(mypath):
    (dirpath, dirnames, filenames) = os.walk(mypath).next()
    return filenames


if __name__ == '__main__':
    main()

如您所见,该代码未注释。 但是请随时询问是否不清楚;)

问题解决了!

import os
import shutil

srcpath = "C:\Users\joshuarb\Desktop\Python_Test\UnorganizedImages"
srcfiles = os.listdir(srcpath)

destpath = "C:\Users\joshuarb\Desktop\Python_Test\OrganizedImages"

# extract the three letters from filenames and filter out duplicates
destdirs = list(set([filename[0:8] for filename in srcfiles]))


def create(dirname, destpath):
    full_path = os.path.join(destpath, dirname)
    os.mkdir(full_path)
    return full_path

def move(filename, dirpath):
    shutil.move(os.path.join(srcpath, filename)
            ,dirpath)

# create destination directories and store their names along with full  paths
targets = [
    (folder, create(folder, destpath)) for folder in destdirs
]

for dirname, full_path in targets:
    for filename in srcfiles:
        if dirname == filename[0:8]:
           move(filename, full_path)

暂无
暂无

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

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