使用Python将某些文件从一个文件夹复制到另一个文件夹

6

我正在尝试从一个文件夹复制特定的文件到另一个文件夹。这些文件名在一个shapefile的属性表中。

我已经成功完成将文件名写入.csv文件并列出包含要传输文件名列表的列。但之后我无法读取这些文件名以将它们复制到另一个文件夹。我已经阅读了有关使用Shutil.copy/move的文章,但不确定如何使用它。任何帮助都将不胜感激。以下是我的脚本:

import arcpy
import csv
import os
import sys
import os.path
import shutil
from collections import defaultdict
fc = 'C:\\work_Data\\Export_Output.shp'
CSVFile = 'C:\\wokk_Data\\Export_Output.csv'
src = 'C:\\UC_Training_Areas'
dst = 'C:\\MOSAIC_Files'

fields = [f.name for f in arcpy.ListFields(fc)]
if f.type <> 'Geometry':
    for i,f in enumerate(fields):

        if f in (['FID', "Area", 'Category', 'SHAPE_Area']):
            fields.remove (f)    

with open(CSVFile, 'w') as f:
f.write(','.join(fields)+'\n') 
with arcpy.da.SearchCursor(fc, fields) as cursor:
    for row in cursor:
        f.write(','.join([str(r) for r in row])+'\n')

f.close()


columns = defaultdict(list) 
with open(CSVFile) as f:
  reader = csv.DictReader(f) 
  for row in reader: 
      for (k,v) in row.items(): 
         columns[k].append(v) 


print(columns['label'])

1
您可能需要编辑您的代码,以便可以通过复制/粘贴运行。缩进等方面现在有些问题。此外,当您使用 with(open(filename, 'w') as f:.... 时,您不需要使用 f.close()。当您退出 with 块时,文件将自动关闭。最后,一个问题...在这个例子中,最后一行打印的文本 print(columns['label']) 是您想要复制到目标目录的文件名吗?否则,我很好奇。 - OYRM
3个回答

3

如果有一个名为columns['label']的文件,您可以使用以下方法移动文件:

srcpath = os.path.join(src, columns['label'])
dstpath = os.path.join(dst, columns['label'])
shutil.copyfile(srcpath, dstpath)

2

这是我用来解决问题的脚本:

import os
import arcpy
import os.path
import shutil
featureclass = "C:\\work_Data\\Export_Output.shp"
src = "C:\\Data\\UC_Training_Areas"
dst = "C:\\Data\\Script"

rows = arcpy.SearchCursor(featureclass)
row = rows.next()
while row:
     print row.Label
     shutil.move(os.path.join(src,str(row.Label)),dst)
     row = rows.next()

1
想象一下这样的情况,源和目标都在本地。假设你想将文件从图片文件夹复制到位于计算机上某处的图像文件夹中的目标位置。
X是您的计算机名称
Z是文件名
import os;
import shutil;
import glob;

source="C:/Users/X/Pictures/test/Z.jpg"
dest="C:/Users/Public/Image"

    if os.path.exists(dest):
    print("this folder exit in this dir")
else:
    dir = os.mkdir(dest)

for file in glob._iglob(os.path.join(source),""):
    shutil.copy(file,dest)
    print("done")

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接