1.学习题目:python整理桌面,让桌面干净清爽,井井有条。

2.知识领域:python实际应用

3.知识内容:

电脑用的时间长了,桌面各种文件杂乱无章,本案例将实现桌面所有文件按文件类型分类整理。效果如下:

①导入所需py库

import os

import shutil

②获取电脑桌面路径,并创建clean文件夹

#获取到桌面路径

desktop = os.path.join(os.path.expanduser('C:\\Users\\yg'),'Desktop')

#print(desktop)

#创建文件夹

name = input('输入文件夹的名字:')

clean = os.path.join(desktop,name)

#判读路径是否存在

isExist = os.path.exists(clean)

if isExist == False:

    os.mkdir(clean)

③读取所有文件的文件名

#获取文件

name_list = os.listdir(desktop)

④判断是文件还是文件夹

#判断是文件还是文件夹

    file_path = os.path.join(desktop,file)

⑤分割文件扩展名,按扩展名创建文件夹

#分割文件名

        fileExpand = os.path.splitext(file)[1]

        #扩展名字符串切片

        fileExpand = fileExpand[1:]

        #按照扩展名创建文件夹

        expand_file_dir = os.path.join(clean,fileExpand)

        if not os.path.exists(expand_file_dir):

            os.mkdir(expand_file_dir)

⑥移动文件到整理文件夹

#移动文件

        shutil.move(file_path,expand_file_dir)

======================================================================================

完整python代码:

 

import os
import shutil
#获取到桌面路径
desktop = os.path.join(os.path.expanduser('C:\\Users\\yg'),'Desktop')
#print(desktop)
#创建文件夹
name = input('输入文件夹的名字:')
clean = os.path.join(desktop,name)
#判读路径是否存在
isExist = os.path.exists(clean)
if isExist == False:
    os.mkdir(clean)
#获取文件
name_list = os.listdir(desktop)
#print(name_list)
#将文件分类
for file in name_list:
    #判断是文件还是文件夹
    file_path = os.path.join(desktop,file)
    if not os.path.isfile(file_path):
        continue
    elif os.path.isfile(file_path):
        #分割文件名
        fileExpand = os.path.splitext(file)[1]
        #扩展名字符串切片
        fileExpand = fileExpand[1:]
        #按照扩展名创建文件夹
        expand_file_dir = os.path.join(clean,fileExpand)
        if not os.path.exists(expand_file_dir):
            os.mkdir(expand_file_dir)
        #移动文件
        shutil.move(file_path,expand_file_dir)

Logo

腾讯云面向开发者汇聚海量精品云计算使用和开发经验,营造开放的云计算技术生态圈。

更多推荐