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(),无需引包 ...
随机推荐
- Linux tmux 使用指南
注意:本文内容适用于 Tmux 2.3 及以上的版本,但是绝大部分的特性低版本也都适用,鼠标支持.VI 模式.插件管理在低版本可能会与本文不兼容. Tmux 快捷键 & 速查表 启动新会话: ...
- java中数据类型的范围
前言:最近:本菜鸡在准备pat,可以每次遇到数据类型的时候都得去查找范围,因此本着学习的目的,来总结一下java中的数据类型. 因此我用mindManager做了一个思维图
- 提示AttributeError: 'module' object has no attribute 'HTTPSHandler'解决方法
今天在新机器上安装sqlmap,运行提示AttributeError: 'module' object has no attribute 'HTTPSHandler' 网上找了找资料,发现一篇文章ht ...
- mybatis传单个参数,和<if>标签同时使用的问题
// Mapper.java EmerEvent selectByAlarmId(Integer alarmId); // Mapper.xml <select id="selectB ...
- Change runlevel on CentOS 6.9/CentOS 7.5
1:CentOS 6.9 # 0 - halt (Do NOT set initdefault to this) # 1 - Single user mode # 2 - Multiuser, wit ...
- linux系统环境下的静态库和动态库的制作
linux系统下的应用编程需要系统提供的库文件,包括静态库或动态库.不管是静态库还是动态库,都是编译好的二进制文件.在我们编译程序时要链接的目标文件,静态库是链接的时候直接编译到程序里,和程序成为一体 ...
- UIDynamic-吸附-重力-碰撞-物理仿真动画
现实生活中: 运动场==物理仿真器 跑步==物理仿真行为 人==仿真元素 创建步骤: 1.创建物理仿真器,并且指定仿真范围 2.创建物理仿真行为,并且指定仿真元素 3.将物理仿真行为添加到仿真器中 D ...
- Vue性能优化之组件按需加载(以及一些常见的性能优化方法)
关于Vue中的按需加载我就简单介绍一下:大概就是我们所有的东西都会在app.js里面,但是我们并不需要把所有的组件都一次性加载进来,我们可以在需要它的时候再将它加载进来,话不多说,开车! 1.webp ...
- 纯js轮播图练习-2,js+css旋转木马层叠轮播
基于css3的新属性,加上js的操作,让现在js轮播图花样越来越多. 而现在出现的旋转木马层叠轮播的轮播图样式,却是得到了很多人都喜爱和投入使用. 尤其是在各大软件中,频繁的出现在大家的眼里,在web ...
- Linux入门——vsftpd
vsftpd Introduction vsftpd是一款在Linux发行版中最受推崇的FTP服务器程序.特点是小巧轻快,安全易用. vsftpd 的名字代表"very secure FTP ...