当前位置:网站首页>Read the root directory of the folder, write txt and generate random samples

Read the root directory of the folder, write txt and generate random samples

2022-07-03 20:48:00 Bright moon drunk windowsill

adopt python It is really convenient to write some scripts to realize the data processing function , Record the present first , Follow up supplement and improvement

1. Read all data in the folder and take random samples

notes : Main call os The file operation function of the Library , If you want to master the degree, you can realize a small function by yourself, and you will soon understand its basic principle , When writing code, you need to pay attention to the up and down alignment and spaces , Otherwise, it will report a mistake , Then, be careful about the coding when reading and writing Chinese paths , The other is string operation , The specific implementation is as follows :

# -*- coding:UTF-8 -*-
import os
import random
dirname = "...folder"
txt_path='F:/code/Pycham/list.txt'
txt_file = open(txt_path,'w')
imglist=[]

def traverse_path(file_path):
    files = os.listdir(file_path)
    for fi in files:
        fi_d = os.path.join(file_path, fi)
        if os.path.isdir(fi_d):

            traverse_path(fi_d)
        else:
            img_name=os.path.join(file_path, fi_d)
            #print(img_name)
            if img_name[-4:]=='tiff':
                #print(img_name)
                txt_file.write(img_name)
                txt_file.write('\n')
    # for i in len(lists):
    # print(lists(i))
#print(" Number of read images :",len(imglist))
traverse_path(dirname)

# Number of random samples 
sample_file='F:\code\Pycham\sample.txt'
n=1000
f=open(txt_path,encoding='gbk')
lines=f.readlines()
list=[]
for line in lines:
    print(line)
    list.append(line)
print(" The total number of samples :",len(list),"  Number of samples :",n)
g=open(sample_file,'w')
a=random.sample(list,n)# Random sampling n That's ok 
for i in a:
    g.write(i)

f.close()
g.close()

原网站

版权声明
本文为[Bright moon drunk windowsill]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202142355405699.html