python常用文件读写

9人阅读 评论(0) 收藏 举报

1.新建一个txt文件并写入

    


f = open("mapping2.txt", "w+")
f.write(str(mapping))
f.close()


2.一个文件夹中有多个子文件夹,每个子文件夹中有多个文件,遍历每个子文件夹的内容


if not os.path.exists(new_folder):
        os.mkdir(new_folder)

    用于判断一个文件是否存在


# encoding:utf-8
import os
import shutil


path1="/home/xionglin/274G2/face0413/dataset"
dst_path="/home/xionglin/274G2/face0413/val"

fs1 = os.listdir(path1)
# fs2 = os.listdir(path2)

for imagefolder in fs1:
    print imagefolder
    new_folder=os.path.join(dst_path,imagefolder)
    print new_folder
    if not os.path.exists(new_folder):
        os.mkdir(new_folder)

    path2 = os.path.join(path1, imagefolder)
    fs2=os.listdir(path2)
    # # for pic in imagefolder:
    print len(fs2)
    # print type(str(path2))
    total_num=len(fs2)
    threshold=int(total_num*0.5)
    print threshold
    num=0
    for pic in fs2:
        # print type(pic)
        # print os.path.join(new_folder,pic)
        if num<=threshold:
            num+=1
            shutil.move(os.path.join(path2,pic), os.path.join(new_folder, pic))
        else:break


查看评论
    个人资料
    等级:
    访问量: 0
    积分: 22
    排名: 0
    文章分类
    文章存档