以下练习,文件名、函数名、变量名有许多不规范的地方,但是也是练习python脚本,就不修正了,在Linux环境上都能成功执行。

小标题不足以代表脚本功能,具体参看描述,有一些也没有按照要求写在,主要是自己练习。

一、模糊搜索文件

下载并解压文件素材压缩包

https://video.mugglecode.com/files.zip

使用Python筛选出符合特征的文件:

1.除了gif类型之外的其他类型

2.名字中包含有关键词project30或者commercial

Python实现。

#!/usr/bin/env python3

# -*- coding: utf-8 -*-

import requests

import os

import zipfile

import shutil

file_url = 'https://video.mugglecode.com/files.zip'

file_name = 'files.zip'

files_path = r'./files'

# 根据url下载文件

r = requests.get(file_url)

with open(file_name, 'wb') as code:

code.write(r.content)

# 解压zip文件

f = zipfile.ZipFile(file_name, 'r')

for file in f.namelist():

f.extract(file, './')

# 会把目录下所有文件和文件夹名存入列表

files = os.listdir(files_path)

for file in files:

if not file.endswith('.gif') and (file.find('project30') != -1 or file.find('commercial') != -1):

print(file)

os.remove(file_name)

shutil.rmtree(files_path)

二、文件按后缀归类

下载并解压件素材压缩包

https://video.mugglecode.com/script_project1_files.zip

根据后缀名,将相同后缀名文件,分类到该后缀名目录中

Python实现。

#!/usr/bin/env python3

# -*- coding: utf-8 -*-

import os

import shutil

path = './files/'

files = os.listdir(path)

for file in files:

suffix = file.split('.')[-1]

if not os.path.lexists(path + suffix):

os.mkdir(path + suffix)

shutil.move(path + file, path + suffix)

三、文件归类

下载并解压件素材压缩包

https://video.mugglecode.com/problem2_files.zip

使用Python进行如下操作:

1. 把jpg、png、gif文件夹中的所有文件移动到image文件夹中,然后删除jpg、png、gif文件夹

2. 把doc、docx、md、ppt文件夹中的所有文件移动到document文件夹中,然后删除doc、docx、md、ppt文件夹

Python实现。

#!/usr/bin/env python3

# -*- coding: utf-8 -*-

import os

import shutil

path = './files/'

dst_dirs = ('image', 'document')

src_martix = (('jpg', 'png', 'gif'), ('doc', 'docx', 'md', 'ppt'))

# 生成目标目录,如果存在则删除后建立

for dst_dir in dst_dirs:

if os.path.exists(dst_dir):

shutil.rmtree(dst_dir)

os.mkdir(dst_dir)

for i in range(0,2):

src_dirs = src_martix[i]

for src_dir in src_dirs:

files = os.listdir(path + src_dir)

for file in files:

print("move:%s->%s" % (path + src_dir + r'/' + file, dst_dirs[i]))

shutil.move(path + src_dir + r'/' + file, dst_dirs[i])

shutil.rmtree(path)

四、zip文件

zip素材包

https://video.mugglecode.com/script_project3_files.zip

监控某目录,如果出现zip压缩文件,自动解压并删除原始zip压缩包

Python实现。

#!/usr/bin/env python3

# -*- coding: utf-8 -*-

import os

import shutil

import time

def scan_dir():

# os.listdir(),不填参数,表示列出当前目录下的文件信息

for file in os.listdir():

if file.endswith('.zip'):

return file

def unzip(file):

dir_name = file.split('.')[0]

path = './' + dir_name

os.mkdir(path)

shutil.unpack_archive(file, path)

os.remove(file)

if __name__ == "__main__":

while True:

file = scan_dir()

if file:

print('')

unzip(file)

time.sleep(5)

五、自动压缩文件

图片素材压缩包,下载后解压使用

https://video.mugglecode.com/image.zip

监测image文件夹,如果包含的文件大于等于5个,则将这些文件压缩到archive1.zip文件中,并删除原始文件。

再次监测到文件多于5个的时候,生成archive2.zip压缩包,以此类推。

Python实现,没有按需求做,而是改为5个文件打一个zip包。

#!/usr/bin/env python3

# -*- coding: utf-8 -*-

import os

import shutil

import time

path = './image/'

tmp_path = './tmp/'

def scan_image_dir():

files = os.listdir(path)

if len(files) >= 5:

return files[:5]

def zip(zip_name, files):

os.mkdir(tmp_path)

for file in files:

shutil.move(path + file, tmp_path + file)

shutil.make_archive(zip_name, 'zip', tmp_path)

shutil.rmtree(tmp_path)

if __name__ == "__main__":

archive_count = 1

while True:

zip_name = 'archive' + str(archive_count)

files = scan_image_dir()

if files:

zip(zip_name, files)

archive_count += 1

print(files, end='')

print('已压缩')

time.sleep(5)

六、删除重复文件

下载并解压这个文件素材压缩包

https://video.mugglecode.com/problem3_files.zip

删除重复的文件,包括不同文件夹内的重复文件

Python实现。

#!/usr/bin/env python3

# -*- coding: utf-8 -*-

import os

import hashlib

files_path = './files'

file_list = list()

def get_files_list(path):

files = os.listdir(path)

for file in files:

if os.path.isdir(path + os.path.sep + file):

get_files_list(path + os.path.sep + file)

else:

file_list.append(path + os.path.sep + file)

def md5(file):

hash_md5 = hashlib.md5()

with open(file, "rb") as f:

for chunk in iter(lambda: f.read(4096), b""):

hash_md5.update(chunk)

return hash_md5.hexdigest()

def get_files_dict(file_list):

file_dict = dict()

for file in file_list:

file_md5 = md5(file)

if file_dict.get(file_md5) is None:

file_dict.setdefault(file_md5, file)

return file_dict

def dump_file_list(file_dict, file_list):

for md5_key in file_dict:

if file_dict[md5_key] in file_list:

file_list.remove(file_dict[md5_key])

return file_list

def del_file(file_list):

for file in file_list:

os.remove(file)

if __name__ == '__main__':

get_files_list(files_path)

file_dict = get_files_dict(file_list)

file_list = dump_file_list(file_dict, file_list)

print("待删除文件列表:%s" % file_list)

del_file(file_list)

主要是os、shutil相关函数及基本结构的练习。

python文件的基本操作_「Python」 - 文件基本操作相关推荐

  1. python读文件去除空行_「34」Python文件操作经典案例:CSV文件的读与写

    [1]认识CSV文件 CSV是Comma Separated Values的缩写,它是逗号分隔符文本格式,常用于数据交换.Excel文件和数据库数据的导入和导出. 鉴于CSV的应用场景,编程人员与它打 ...

  2. python做地图导航_「Python」利用高德地图做你想做之事

    玩grasshopper基本上都知道OpenStreetMap 这个地图网站,毕竟有一个好用的地图插件,可以在Rhino中绘制出所需,但是一个不好的地方就在于国内的数据量太少,无法满足我们的需求. 此 ...

  3. python字符串的内部函数_「Python」字符串操作内置函数

    目录: capitalize casefold center count encode decode endswith expandtabs find format format_map index ...

  4. python 基金量化分析_「Python量化」怎么在基金定投上实现收益最大化

    我们也会有恐惧和贪婪,只不过在别人贪婪的时候我们恐惧,在别人恐惧的时候我们贪婪.--巴菲特 引言 继上一篇文章< Python数说指数定投策略>,今天为大家分享一篇推文(原文来源:SAMs ...

  5. python闹钟界面程序_「Python编程」自由管理时间之编写一个小闹钟起床

    Python_时间管理 代码中的时间时间戳(Timestamp):1473525444 时间字符串(Format String):2015-02-14 11:25:11 结构化时间:(struct_t ...

  6. python建立空集合_「python」集合类型及操作

    目录: 集合类型定义 集合操作符 集合处理方法 集合类型应用场景 1 集合类型定义 集合是多个元素的无序组合 集合用大括号 {} 表示,元素间用逗号分隔 建立集合类型用 {} 或 set() 建立空集 ...

  7. python实习内容过程_「Python实践」学习之路

    一.列表内容对比 方式一: import operator l1 = ['a','b','c'] l2 = ['a','d','e'] print(operator.lt(l1,l2)) 运行结果为T ...

  8. python从零开始到精通_「Python 入门学习指南」0基础小白助你从入门到精通!

    Python比较简单,非常适合初学者入门,内置了各种库,还有丰富的大约13万第三方库,掌握了语法和编程思维后,可以直接使用这些库做出自己的产品.这篇 Python 入门学习指南,针对没有任何编程经验. ...

  9. python输入城市名称_「Python」每日一练:列表创建身份证城市代码

    编程题 列表创建之身份证域市代号 现有湖南省各城市所对应的身份证代号的字符串,现要求将代号及所对应的城市分别保存到2个列表中,要求相应代号和其城市的素引一致.id的数据如下: id="430 ...

最新文章

  1. java datasource mysql_Java MysqlDataSource類代碼示例
  2. 带你玩玩转 MySQL 查询
  3. Window_Open详解
  4. 第17课:基于 CRF 的中文句法依存分析模型实现
  5. masm5安装教程_汇编语言程序环境搭建masm+debug64位 win10/7
  6. Understanding Clouds from Satellite Images语义分割比赛中train_test_split与stratify配合使用
  7. CentOS7查看开放端口命令及开放端口号
  8. 链家程序员删库跑路失败!被判 7 年
  9. 关于运行微信小程序报错 [微信小程序开发者工具] Error: read EBADF
  10. 硬盘的那些事(主分区、扩展分区、逻辑分区、活动分区、系统分区、启动分区、引导扇区、MBR等
  11. 学计算机高中应选什么科目,新高考选哪些科目可以报计算机?高中生如何进步?...
  12. 反应堆Reactor模式
  13. 浅谈计算机专业的毕业生如何提高自身素质
  14. 疫情之后,各地智慧灯杆政策与项目发布情况汇总
  15. android企业自定义桌面
  16. esaywechat 微信公众号jsapi支付
  17. 如何学会600多种编程语言
  18. 3.4.3 Electric Fence电网 USACO(毕克定理) USACO
  19. JavaPoet使用攻略
  20. 抖音主页如何添加官网链接

热门文章

  1. POJ 2788 ipnetworks 计算机网络相关知识
  2. PowerDesigner 中的name与comment转换(转)
  3. svn: E180001: Unable to open an ra_local session to URL问题解决方案
  4. 使用Ext JS,不要使用页面做组件重用,尽量不要做页面跳转
  5. mysql增备脚本--xtrabackup实现
  6. 软件测试中开发团队和测试团队的职责
  7. 层遇到select框时[收藏]
  8. 信息学奥赛一本通(2073:【例2.16 】三角形面积)
  9. 信息学奥赛一本通(1404:我家的门牌号)
  10. Lines(HDU-5124)