我有一个文件列表,如下所示:
LT50300281984137PAC00_sr_band1.tif
LT50300281984137PAC00_sr_band2.tif
LT50300281984137PAC00_sr_band3.tif
LT50300281985137PAC00_sr_band1.tif
LT50300281985137PAC00_sr_band2.tif
LT50300281985137PAC00_sr_band3.tif
我创建了名为_1984_
和_1985_
的文件夹,我希望将包含相应字符串的所有文件(只有1984年和1985年,结尾的_)发送到相应的文件夹。我有从1984年到2011年的年份,所以如果可能的话我想用某种循环来做这件事。现在我将文件放在一个列表中,我将使用此代码将各个年份保存到单个文件夹中:
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')
我真的希望自动化这一年,但这是我被卡住的地方。因此,将包含1984
的所有文件复制到相应的文件夹后,1985
也会如此,依此类推。
编辑:
此代码:
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)
返回:
AttributeError: 'module' object has no attribute 'getcwd'
答案 0 :(得分:2)
假设您将所有这些文件放在一个目录中,并且您希望在同一目录中创建所有文件夹。然后,这应该这样做:
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))