我有一个文件夹,文件名如下:
Sheyenne_19840517.dat
Sheyenne_19840517.hdr
Sheyenne_19840704.dat
Sheyenne_19840704.hdr
Sheyenne_19840906.dat
Sheyenne_19840906.hdr
Sheyenne_19850520.dat
Sheyenne_19850520.hdr
Sheyenne_19850621.dat
Sheyenne_19850621.hdr
Sheyenne_19860726.dat
Sheyenne_19860726.hdr
Sheyenne_19860827.dat
Sheyenne_19860827.hdr
Sheyenne_19870830.dat
Sheyenne_19870830.hdr
Sheyenne_19870915.dat
Sheyenne_19870915.hdr
文件名末尾的数字代表日期。我想按月分开文件。因此,5月(或05)中的所有文件都会获得自己的文件夹,依此类推。我正在尝试使用此代码:
import os
import shutil
hank_out=r'F:\Sheyenne\ROI\All_Sheyenne_julian\By_Month\NDVI'
pth=r'F:\Sheyenne\ROI\All_Sheyenne_julian\NDVI'
for f in os.listdir(pth):
month=os.path.basename(f)[-8:-6]
if not os.path.isdir(os.path.join(hank_out,month)):
os.mkdir(os.path.join(hank_out, month))
shutil.copy(f, os.path.join(hank_out, month))
这仅复制一个月遇到的第一个文件。因此,每个文件夹中只有一个文件用于输出,它是该月首次遇到的文件。我不确定为什么没有复制所有文件。