如何解决如何循环遍历生成器,然后生成生成器?
我想将在目录中循环的文件复制到一个新文件夹中,并且我还想将文件路径添加到 csv,但我似乎无法在同一个函数中同时执行这两个操作。
import shapefile
import shutil,os
import csv
rasters = []
top = r"./test1"
def copy_filepaths(top):
for dirpath,dirs,files in os.walk(top):
if '__' in dirpath:
continue
shapefiles = filter(lambda f: f.endswith(".shp") and not f.startswith('.'),files) # shapefiles only
full_path_shapefiles = (os.path.join(dirpath,f) for f in shapefiles) # build the full path
for shapefile in full_path_shapefiles:
shutil.copy(shapefile,'./test1_copy')
yield from full_path_shapefiles
filepaths = copy_filepaths(top)
for filepath in filepaths:
with open(r'./shp_walker.csv','a+',newline='') as f:
write = csv.writer(f)
write.writerow([filepath])
解决方法
import shapefile
import shutil,os
import csv
rasters = []
top = r"./test1"
def copy_filepaths(top):
for dirpath,dirs,files in os.walk(top):
if '__' in dirpath:
continue
shapefiles = filter(lambda f: f.endswith(".shx") and not f.startswith('.'),files) # shapefiles only
full_path_shapefiles = (os.path.join(dirpath,f) for f in shapefiles) # build the full path
for shapefile in full_path_shapefiles:
shutil.copy(shapefile,'./test1_copy')
yield shapefile
filepaths = copy_filepaths(top)
for filepath in filepaths:
with open(r'./shp_walker.csv','a+',newline='') as f:
write = csv.writer(f)
write.writerow([filepath])
,
您始终可以将写操作移到 copy_filepaths()
函数中。您不需要在这里使用生成器。看起来 test1_copy
也经常被覆盖,不确定这是不是故意的。
import shapefile
import shutil,files in os.walk(top):
if '__' in dirpath:
continue
shapefiles = filter(lambda f: f.endswith(".shp") and not f.startswith('.'),'./test1_copy')
with open(r'./shp_walker.csv',newline='') as f:
write = csv.writer(f)
write.writerow([shapefile])
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。