Reputation: 3577
I have a list of files which looks like this:
LT50300281984137PAC00_sr_band1.tif
LT50300281984137PAC00_sr_band2.tif
LT50300281984137PAC00_sr_band3.tif
LT50300281985137PAC00_sr_band1.tif
LT50300281985137PAC00_sr_band2.tif
LT50300281985137PAC00_sr_band3.tif
I have folders created titled _1984_
and _1985_
and I want to send all files which contain those respective strings (well just 1984 and 1985 with out the _ on the ends) to the corresponding folder. I have years from 1984-2011 so if possible I would like to do this with some sort of loop. Right now I have the files in a list and I am pulling out individual years and saving them to individual folders with this code:
import arcpy, os, shutil
#directory where .tif files are stored
in_raster='F:\Sheyenne\Atmospherically Corrected Landsat\hank_masked\just_bands'
#directory where files are copied
out_raster='F:\Sheyenne\Atmospherically Corrected Landsat\hank_masked\Years\_1984_'
#pull out year of interest as wildcard
list1=arcpy.ListRasters("*1984*")
for raster in list1:
source_path = os.path.join(in_raster, raster)
out_path=os.path.join(out_raster,raster)
shutil.copy(source_path, out_path)
print ('Done Processing')
I would really like to automate this for all years though and this is where I am stuck. So once all files containing 1984
are copied to appropriate folder, the same is done for 1985
and so on.
Edit:
This code:
import os, shutil, glob
for fpath in glob.glob('F:\Sheyenne\Atmospherically Corrected Landsat\hank_masked\just_bands/*.tif'): # this returns a list of the CURRENT contents. Therefore, there is no need to sanitize for the directories that we will later create
year = os.path.basename(fpath)[9:13]
if not os.path.isdir(os.path.join(os.path.getcwd(), year)):
os.mkdir(year)
shutil.move(fpath, year)
returns:
AttributeError: 'module' object has no attribute 'getcwd'
Upvotes: 0
Views: 2254
Reputation: 114035
Let's say you have all these files in one directory, and you want to create all your folders in the same directory. Then, this should do it:
import os
import glob
import shutil
outputDir = os.getcwd()
for fpath in glob.glob('*.tif'): # this returns a list of the CURRENT contents. Therefore, there is no need to sanitize for the directories that we will later create
year = os.path.basename(fpath)[9:13]
if not os.path.isdir(os.path.join(outputDir, year)):
os.mkdir(os.path.join(outputDir, year))
shutil.move(fpath, os.path.join(outputDir, year))
Upvotes: 2