将基于文件名的文件保存到各个文件夹

时间:2015-08-13 19:17:55

标签: python

我有480个文件的列表,我想根据文件名将它们保存到80个文件夹。文件名的示例是:

when(this.store.get("index")).then(onItem);

我想将前21个字符[0:21]的切片中具有匹配字符的文件保存到具有相同名称的文件夹中。例如:

(defn subs* [s start end]
  (if (neg? start)
    (subs s (+ (.length s) start) end)
    (subs s start end)))

会进入名为LT50300281984137PAC00_sr_band1.tif LT50300281984137PAC00_sr_band2.tif LT50300282007136PAC01_sr_band1.tif LT50300282007136PAC01_sr_band2.tif LT50300282002138LGS01_sr_band1.tif LT50300282002138LGS01_sr_band2.tif

的文件夹中

LT50300281984137PAC00_sr_band1.tif
LT50300281984137PAC00_sr_band2.tif 

会进入名为LT50300281984137PAC00

的文件夹中

我已使用此代码创建了文件夹:

LT50300282007136PAC01_sr_band1.tif
LT50300282007136PAC01_sr_band2.tif

现在我想把每个带有' band'在我上面显示的名称中,将其存储在正确的文件夹中,但这就是我被困住的地方

3 个答案:

答案 0 :(得分:1)

import arcpy, os

original_path = r'F:\Sheyenne\Atmospherically Corrected Landsat\hank_masked\Band 1'
#pathway where there are only 80 .tif files, one for each landsat scene
arcpy.env.workspace=original_path
#list of rasters in above pathway
list1 = arcpy.ListRasters("*.tif")
#output save pathway
main_path=r'F:\Sheyenne\Atmospherically Corrected Landsat\Individual Scenes\Main'

#create folder for each landsatscene containing first 21 characters
for raster in list1:

    source_path = os.path.join(original_path, raster)
    dir_name=split("_")[0]
    destination_path=os.path.join(main_path, dir_name)

    if not os.path.isdir(destination_path):
        os.makedirs(destination_path)

    destination_path = os.path.join(destination_path, raster)

    if not os.path.exists(destination_path):
        os.rename(source_path, destination_path)

答案 1 :(得分:1)

使用.tif文件在同一目录中运行此脚本。它假定您已经拥有了目录,正如您在问题中提到的那样。

import glob
import os

for source in glob.glob("*band*.tif"):
    target = os.path.join( source[:21], source )
    os.rename(source, target)

答案 2 :(得分:0)

由于您已经创建了该文件夹,因此您应该能够在循环内使用os.rename命令(如链接中所示):How to move a file in Python

# Create a var to store the original path
original_path = r'F:\Sheyenne\Atmospherically Corrected Landsat\hank_masked\Band 1'
arcpy.env.workspace= original_path

#list of rasters in above pathway
list1 = arcpy.ListRasters("*.tif")

#output save pathway
mainpath=r'F:\Sheyenne\Atmospherically Corrected Landsat\Individual Scenes\Main'

#create folder for each landsatscene containing first 21 characters
for raster in list1:
    rasterName=raster[0:21]
    if raster.startswith(rasterName.split("_")[0]):
        final_path=os.path.join(mainpath,rasterName)
        os.makedirs(final_path)
        # create a path for the new file
        new_file = os.path.join(final_path, 'new_file_name.tif')
        # create a path for the old file
        old_file = os.path.join(original_path, raster)
        # rename (move) the old file to the new file
        os.rename(old_file, new_file)