Python 循环遍历子文件夹并复制具有特定扩展名的文件
我有一个父文件夹,我们称之为“工作区”。在此父文件夹中,存在子文件夹,这些子文件夹具有具有特定命名约定的其他子文件夹。它看起来像这样:Python 循环遍历子文件夹并复制具有特定扩展名的文件,python,python-2.7,python-requests,shutil,arcpy,Python,Python 2.7,Python Requests,Shutil,Arcpy,我有一个父文件夹,我们称之为“工作区”。在此父文件夹中,存在子文件夹,这些子文件夹具有具有特定命名约定的其他子文件夹。它看起来像这样: - Workspace - Subfolder A - Name - Image - Class - Subfolder B - Name - Image - Class - Subfolder
- Workspace
- Subfolder A
- Name
- Image
- Class
- Subfolder B
- Name
- Image
- Class
- Subfolder C
- Name
- Image
- Class
我需要某种类型或方向的帮助来编写一个脚本,在工作区内迭代a-C,并将每个子文件夹的“images”文件夹中的所有文件复制到新的目标
这就是我到目前为止所做的:
import os
import arcpy
import shutil
import fnmatch
workspace = "source"
pfolder = "rootdir"
files = os.listdir(workspace)
print (files)
test = workspace + "\\scratch.gdb"
if os.path.exists(test):
print ("Scratch GDB already exists")
shutil.rmtree(test)
scratch = arcpy.CreateFileGDB_management(workspace,"scratch")
print ("Original Scratch GDB removed and new GDB created ")
else:
scratch = arcpy.CreateFileGDB_management(workspace,"scratch")
print ("Scratch GDB has been created")
def main():
for dirname, dirnames, filenames in os.walk(pfolder):
for file in filenames:
if fnmatch.fnmatch(file,"*.jpg")==True:
shutil.copy2(file,scratch)
print("Files have been copied!")
else:
print("Error in copying files")
我想复制该子目录中的所有jpg文件,并将它们放在地理数据库中。由于某些原因,它不会运行执行循环和复制的代码行。如果要在地理数据库中输入光栅文件,Shutil可能不起作用 下面的代码是您的代码,只需稍加修改(例如使用CopyRaster_管理而不是copy2)即可工作,因此它可能不是最好的代码,因为我并不担心这一点,但它可以工作:
import os
import arcpy
import shutil
import fnmatch
workspace = "C:\\Teste\\"
pfolder = r'C:\Teste\\'
files = os.listdir(workspace)
print (files)
tests = workspace + "\\scratch.gdb"
sGdbP = "C:\\Teste\\scratch.gdb\\"
if os.path.exists(tests):
print ("Scratch GDB already exists")
shutil.rmtree(tests)
scratch = arcpy.CreateFileGDB_management(workspace,"scratch")
print ("Original Scratch GDB removed and new GDB created ")
else:
scratch = arcpy.CreateFileGDB_management(workspace,"scratch")
print ("Scratch GDB has been created")
for dirname, dirnames, filenames in os.walk(pfolder):
for file in filenames:
if fnmatch.fnmatch(file,"*.tif")==True:
try:
arcpy.env.workspace = dirname
in_data = file
out_data = sGdbP + file[:-4] # cannot use extension
arcpy.CopyRaster_management(in_data, out_data)
except:
print "Raster To Geodatabase example failed."
print arcpy.GetMessages()
print("Files have been copied!")
print "End of script"
在哪里调用
main
函数?