#coding=utf-8
# 作 者 : PeiQi
# 开发时间 : 2021/11/4 0004 上午 8:56
# 文件名称 : random500.PY
# 开发工具 : PyCharm
'''
需求:
随机取指定个数的地块,为了节约计算资源,避免每次计算非验证的地块,首先将随机选取的地块对应的shp文件复制到文件夹中,
每次运行程序,只计算随机获得的地块。
本模块代码的作用:
随机生成指定个数的数字写入.txt文档,并将随机生成的数字对应的.shp文件(8个)复制到指定文件夹中
'''
import random
import os
import shutil
#存放随机得到的文件编号
rand_set=[]
#num没用,只是我用来计数,并且输出到控制台,以方便让我实时了解复制进度
num=0
# txt文档名
full_path = "随机100个地块编号.txt"
#rang()中填写的是需要得到多少个随机数
for i in range(10):
#随机数的取值范围
rand= random.randint(0, 5058)
#将随机数append到rang_set[]中
rand_set.append(rand)
#打开txt文档
file = open(full_path, 'a')
#将随机数写进txt文档
file.write(str(rand)) # msg也就是下面的Hello world!
file.write("\n")
#这个print()没啥用,我就是想在控制台看看随机生成的数
print(sorted(rand_set))
# 很多shp文件的存在的文件夹 from
src_dir_path = 'C:/Users/Administrator/Desktop/0417/5053'
# 存放复制文件的文件夹 to
to_dir_path = 'shp'
#遍历随机数列表
for key_int in rand_set:
num=num+1
print("正在复制第%d个shp" %num)
# 源文件夹中的文件包含字符key则复制到to_dir_path文件夹中
key=str(key_int)
if not os.path.exists(to_dir_path):
print("dir路径不存在,因此创建dir")
os.mkdir(to_dir_path,1)
#遍历from文件夹中的所有文件名
for file in os.listdir(src_dir_path):
#如果from文件夹中的file是个文件,而非文件夹
if os.path.isfile(src_dir_path+'/'+file):
#判断from文件夹中的file名和随机数列表中的元素关系,这个if只能复制八个文件中的七个
if os.path.splitext(file)[0] == key:
shutil.copy(src_dir_path+'/'+file,to_dir_path+'/'+file)
#这个if将复制第八个
elif os.path.splitext(file)[0]== key+".shp":
shutil.copy(src_dir_path + '/' + file, to_dir_path + '/' + file)
假设从文件夹A中随机选取100个文件,复制到文件夹B中
最新推荐文章于 2024-06-16 07:09:52 发布