pyhon文件操作典型代码实现(非常经典!)
1. 编写一个程序,统计当前目录下每个文件类型的文件数,程序实现如图:
实现代码:
import os
all_files = os.listdir(os.chdir("D:\\"))
type_dict = dict()
for each_file in all_files:
if os.path.isdir(each_file):
type_dict.setdefault('文件夹', 0)
type_dict['文件夹'] += 1
else:
ext = os.path.splitext(each_file)[1]
type_dict.setdefault(ext, 0)
type_dict[ext] += 1
for each_type in type_dict.keys():
print('该文件夹下共有类型为【%s】的文件 %d 个' % (each_type, type_dict[each_type]))
2、编写一个程序,计算当前文件夹下所有文件的大小:
import os
all_files = os.listdir(os.chdir("D:\\")) # 使用os.curdir表示当前目录更标准
file_dict = dict()
for each_file in all_files:
if os.path.isfile(each_file):
file_size = os.path.getsize(each_file)
file_dict[each_file] = file_size
for each in file_dict.items():
print('%s【%dBytes】' % (each[0], each[1]))
3、编写一个程序,用户输入文件名以及开始搜索的路径,搜索该文件是否存在。如遇到文件夹,则进入文件夹继续搜索:
import os
def search_file(start_dir, target) :
os.chdir(start_dir)
for each_file in os.listdir(os.chdir("C:\\")) :
if each_file == target :
print(os.getcwd() + os.sep + each_file) # 使用os.sep是程序更标准
if os.path.isdir(each_file) :
search_file(each_file, target) # 递归调用
os.chdir(os.pardir) # 递归调用后切记返回上一层目录
start_dir = input('请输入待查找的初始目录:')
target = input('请输入需要查找的目标文件:')
search_file(start_dir, target)
4、 编写一个程序,用户输入开始搜索的路径,查找该路径下(包含子文件夹内)所有的视频格式文件(要求查找mp4 rmvb, avi的格式即可),并把创建一个文件(vedioList.txt)存放所有找到的文件的路径,程序实现如图:
import os
def search_file(start_dir, target) :
os.chdir(start_dir)
for each_file in os.listdir(os.curdir) :
ext = os.path.splitext(each_file)[1]
if ext in target :
vedio_list.append(os.getcwd() + os.sep + each_file + os.linesep) # 使用os.sep是程序更标准
if os.path.isdir(each_file) :
search_file(each_file, target) # 递归调用
os.chdir(os.pardir) # 递归调用后切记返回上一层目录
start_dir = input('请输入待查找的初始目录:')
program_dir = os.getcwd()
target = ['.mp4', '.avi', '.rmvb']
vedio_list = []
search_file(start_dir, target)
f = open(program_dir + os.sep + 'vedioList.txt', 'w')
f.writelines(vedio_list)
f.close()
5、编写一个程序,用户输入关键字,查找当前文件夹内(如果当前文件夹内包含文件夹,则进入文件夹继续搜索)所有含有该关键字的文本文件(.txt后缀),要求显示该文件所在的位置以及关键字在文件中的具体位置(第几行第几个字符)
import os
def print_pos(key_dict):
keys = key_dict.keys()
keys = sorted(keys) # 由于字典是无序的,我们这里对行数进行排序
for each_key in keys:
print('关键字出现在第 %s 行,第 %s 个位置。' % (each_key, str(key_dict[each_key])))
def pos_in_line(line, key):
pos = []
begin = line.find(key)
while begin != -1:
pos.append(begin + 1) # 用户的角度是从1开始数
begin = line.find(key, begin+1) # 从下一个位置继续查找
return pos
def search_in_file(file_name, key):
f = open(file_name)
count = 0 # 记录行数
key_dict = dict() # 字典,用户存放key所在具体行数对应具体位置
for each_line in f:
count += 1
if key in each_line:
pos = pos_in_line(each_line, key) # key在每行对应的位置
key_dict[count] = pos
f.close()
return key_dict
def search_files(key, detail):
all_files = os.walk(os.curdir)
txt_files = []
for i in all_files:
for each_file in i[2]:
if os.path.splitext(each_file)[1] == '.txt': # 根据后缀判断是否文本文件
each_file = os.path.join(i[0], each_file)
txt_files.append(each_file)
for each_txt_file in txt_files:
key_dict = search_in_file(each_txt_file, key)
if key_dict:
print('================================================================')
print('在文件【%s】中找到关键字【%s】' % (each_txt_file, key))
if detail in ['YES', 'Yes', 'yes']:
print_pos(key_dict)
key = input('请将该脚本放于待查找的文件夹内,请输入关键字:')
detail = input('请问是否需要打印关键字【%s】在文件中的具体位置(YES/NO):' % key)
search_files(key, detail)
pyhon文件操作典型代码实现(非常经典!)的更多相关文章
- C#各种文件操作的代码与注释
C#各种文件操作的代码与注释,具体看下面代码: using System; using System.Collections.Generic; using System.Linq; using Sys ...
- python系列——文件操作的代码
import numpy as np import os,sys #获取当前文件夹,并根据文件名 def path(fileName): p=sys.path[0]+'\\'+fileName ret ...
- java IO流 对文件操作的代码集合
Io流 按照分类 有两种分类 流向方向: 有输入流和输出流 按照操作类型有:字节流和字符流 按照流向方向 字节流的一些操作 //读文件 FileInputStream fis = new FileIn ...
- VS2010/MFC编程入门之四十五(MFC常用类:CFile文件操作类)
上一节中鸡啄米讲了定时器Timer的用法,本节介绍下文件操作类CFile类的使用. CFile类概述 如果你学过C语言,应该知道文件操作使用的是文件指针,通过文件指针实现对它指向的文件的各种操作.这些 ...
- 文件操作(FILE)与常用文件操作函数
文件 1.文件基本概念 C程序把文件分为ASCII文件和二进制文件,ASCII文件又称文本文件,二进制文件和文本文件(也称ASCII码文件)二进制文件中,数值型数据是以二进制形式存储的, 而在文本文件 ...
- PYDay6- 内置函数、验证码、文件操作、发送邮件函数
1.内置函数 1.1Python的内置函数 abs() dict() help() min() setattr() all() dir() hex() next() slice() any() div ...
- (转载)Mac系统下利用ADB命令连接android手机并进行文件操作
Mac系统下利用ADB命令连接android手机并进行文件操作 标签: Mac adb android 2016-03-14 10:09 5470人阅读 评论(1) 收藏 举报 分类: Androi ...
- python系列——文件操作
打开和关闭 示例:python系列——文件操作的代码 打开模式 读取 写入
- python从入门到大神---4、python3文件操作最最最最简单实例
python从入门到大神---4.python3文件操作最最最最简单实例 一.总结 一句话总结: python文件操作真的很简单,直接在代码中调用文件操作的函数比如open().read(),无需引包 ...
随机推荐
- sendmail启动报错
sendmail启动不了,报错如下: 解决方法: 在/etc/mail/sendmail.cf 配置文件中查找 Dj$w,并在此行下面增加这一行. Dj$w. 在/etc/hosts 增加一行 192 ...
- spring配置redis(xml+java方式)(最底层)
条件:引用好架包 <dependency> <groupId>org.springframework.data</groupId> <artifactId&g ...
- HDU 2079 选课时间(普通型 数量有限 母函数)
传送门: http://acm.hdu.edu.cn/showproblem.php?pid=2079 选课时间(题目已修改,注意读题) Time Limit:1000MS Memory Li ...
- react系列(三)组件间通信
组件间通信 React的基本组件元素是一个个组件,组件之间可能存在关联.组合等关系.不同的组件之间,经常会发生数据传递或者交换,我们称之为组件间通信. 根据传递的复杂程度,可以分为三种情况: 父子间通 ...
- ObjC之RunTime(下)
之前通过学习官方文档对runtime有了初步的认识,接下来就要研究学习runtime到底能用在哪些地方,能如何改进我们的程序. 本文也可以从icocoa浏览. Swizzling Swizzling可 ...
- python函数调用时传参方式
位置参数 位置参数需与形参一一对应 def test(a,b) #a,b就是位置参数 print(a) print(b) test(1,2) 关键字参数 与形参顺序无关 def test(x,y) ...
- linux使用logrotate工具管理日志轮替
对于Linux系统安全来说,日志文件是极其重要的工具.logrotate程序是一个日志文件管理工具.用于分割日志文件,删除旧的日志文件,并创建新的日志文件,起到"转储"作用.可以节 ...
- python学习笔记:第19天 类的约束、异常、MD5和logging
目录 一.类的约束 二.异常处理: 三.MD5加密 四.日志(logging模块) 一.类的约束 真正写写项目的代码时都是多人协作的,所以有些地方需要约束程序的结构.也就是说,在分配任务之前就应该把功 ...
- JVM培训序幕篇
明天老王要给我们讲JVM的知识,提前发了一个小Demo给我们看,代码如下: package demo; import java.util.*; public class Demo { public s ...
- 类加载器 ClassLoder详解
一.类加载器定义 从作用的角度来认识类加载器:(根据API文档) 1.类加载器是一个负责加载类的对象,而ClassLoader是一个抽象类.类加载器将xxx.class文件加载到JVM,生成xxx的C ...