1.模块含义:
一个包含所有定义的函数和变量的文件,后缀名是.py。模块可以被别的程序引入,以使用模块中的函数功能。
2.OS模块中用法说明:
(1)os模块中关于文件/目录常用的函数使用方法:
函数名 | 使用方法 |
getcwd() | 返回当前工作目录 |
chdir(path) | 改变工作目录 |
listdir(path='.') | 列举指定目录中的文件名('.'表示当前目录,'..'表示上一级目录) |
mkdir(path) | 创建单层目录,如该目录已存在抛出异常 |
makedirs(path) | 递归创建多层目录,如该目录已存在抛出异常,注意:'E:\\a\\b'和'E:\\a\\c'并不会冲突 |
remove(path) | 删除文件 |
rmdir(path) | 删除单层目录,如该目录非空则抛出异常 |
removedirs(path) | 递归删除目录,从子目录到父目录逐层尝试删除,遇到目录非空则抛出异常 |
rename(old, new) | 将文件old重命名为new |
system(command) | 运行系统的shell命令 |
walk(top) | 遍历top路径以下所有的子目录,返回一个三元组:(路径, [包含目录], [包含文件]) |
以下是支持路径操作中常用到的一些定义,支持所有平台 | |
os.curdir | 指代当前目录('.') |
os.pardir | 指代上一级目录('..') |
os.sep | 输出操作系统特定的路径分隔符(Win下为'\\',Linux下为'/') |
os.linesep | 当前平台使用的行终止符(Win下为'\r\n',Linux下为'\n') |
os.name | 指代当前使用的操作系统(包括:'posix', 'nt', 'mac', 'os2', 'ce', 'java') |
使用示例:
import os#导入os模块
os.getcwd()#获取当前文件目录
os.mkdir('C:\\A')#会在C盘目录下创建一个名为A的文件夹
os.mkdir('C:\\A\\B')#会在C盘目录在名为A的文件夹中创建一个名为B的文件夹
(2)os.path模块中关于路径常用的函数使用方法:
使用示例:
import os
os.path.basename('C:\\A\\B\\C\\test.txt')#结果为:test.txt
os.path.join('C:\\','A','B')#结果为:'C:\\A\\B'
3.用法实例应用:
(1)问题描述:
–>统计当前目录下每个文件类型的文件数
代码实现:
#首先获取当前目录
import os
path_name = os.getcwd()
#获取当前目录中所有文件
file_sum = os.listdir(path_name)
#分离所有文件与扩展名
file_extension = []#文件扩展名
file_name = []#文件名
for i in range(len(file_sum)):
(name, extension) = os.path.splitext(file_sum[i])
file_name.append(name)
file_extension.append(extension)
file_extension_jihe = set(file_extension)
for each in file_extension_jihe:
if each == '':
print('该文件夹共有类型为[文件夹]的文件%d个' % file_extension.count(each))
else:
print('该文件夹共有类型为[%s]的文件%d个' % (each,file_extension.count(each)))
扩展阅读:
#利用字典完成:
#思路:
#例如:最终后缀名组成的列表为:['.txt', '.txt', '.py', '.jpg', '']
extension = ['.txt', '.txt', '.py', '.jpg', '']
type_dict = dict()#存储后缀名:文件个数
for each_extension in extension:
if each_extension == '':
type_dict.setdefault('文件夹',0)
type_dict['文件夹'] += 1
else: type_dict.setdefault(each_extension,0)#setdefault()方法当键不存在于字典中,会将键对应值设置为默认值,否则返回字典中该键对应值
type_dict[each_extension] += 1
print(type_dict)
小结:
[1]文件获取当前目录:
在使用os模块的基础上,使用os.cudir更准确
[2]分离文件名和扩展名:
在使用os模块的基础上,使用os.path.splitext
[3]字典中setdefault函数用法:
setdefault()方法当键不存在于字典中,会将键对应值设置为默认值,否则返回字典中该键对应值
(2)问题描述:
用户输入文件名及开始搜索的路径,搜索文件是否存在。遇到文件夹时继续搜索
实现如下:
请输入待查找的目录:C:\Python33\文件OS系统测试目录
请输入待查找的目标文件:test1-1.txt
C:\Python33\文件OS系统测试目录\test1\test1-1.txt
C:\Python33\文件OS系统测试目录\test1\test1-1\test1-1.txt
代码实现:
#模块引入
import os
start_catalogue = input('请输入待查找的目录:')
file_goal = input('请输入待查找的目标文件:')
def search_file(start_dir, target):
os.chdir(start_dir)#改变工作目录为start_dir
for each_file in os.listdir(os.curdir):#os.curdir指代当前目录
if each_file == target:
print(os.getcwd() + os.sep + each_file)#os.sep输出操作系统特定的路径分隔符(Win下为'\\',Linux下为'/')
if os.path.isdir(each_file):
search_file(each_file, target)#递归调用
os.chdir(os.pardir)#递归后返回上一层目录,os.pardir指代上一层目录
search_file(start_catalogue, file_goal)
小结:
[1]在使用os模块的基础上,os.pardir返回上一层目录,os.curdir返回当前目录
[2]递归调用后要返回上一层目录
(3)问题描述:
完成如下:
请将该脚本放入待查找的文件夹内,请输入关键字:一
请问是否要打印关键字[一]在文件中的具体位置(YES/NO):YES
===========================================
在文件[C:\Python33\编程过程\第十八讲--文件相关\something2.txt]中找到关键字[一]
关键字出现在第[1]行,第[7]个位置
关键字出现在第[4]行,第[3]个位置
关键字出现在第[5]行,第[8]个位置
关键字出现在第[8]行,第[6]个位置
关键字出现在第[9]行,第[3, 7, 11]个位置
关键字出现在第[11]行,第[5]个位置
===========================================
在文件[C:\Python33\编程过程\第十八讲--文件相关\test3\something1.txt]中找到关键字[一]
关键字出现在第[1]行,第[3, 7, 11]个位置
关键字出现在第[3]行,第[5]个位置
关键字出现在第[6]行,第[8]个位置
关键字出现在第[9]行,第[6]个位置
关键字出现在第[10]行,第[7]个位置
关键字出现在第[13]行,第[3]个位置
代码实现:
#模块引入
import os
start_keys = input('请将该脚本放入待查找的文件夹内,请输入关键字:')
choose = input('请问是否要打印关键字[%s]在文件中的具体位置(YES/NO):' % start_keys)
#检测关键字在字符串中出现位置
def location_keys(str1,str2):
location_index = []#存放字符出现位置
a_len = len(str2)
b_len = len(str1)
count = 0
while a_len - count >= b_len:
if str2[count : count+b_len] == str1:
location_index.append(count+1)
count += 1
return location_index
#得到当前文件夹下所有的.txt
#首先得到当前目录
start_catalogue = os.getcwd()
#遍历获得该文件夹下所有.txt文件路径
def file_sum_path(start_catalogue):
sub_catalogue = list(os.walk(start_catalogue))
sub_catalogue_path = []#存储文件目录
sub_catalogue_file = []#存储文件名
for i in range(len(sub_catalogue)):
sub_catalogue_path.append(sub_catalogue[i][0])
sub_catalogue_file.append(sub_catalogue[i][2])
#返回当前文件夹下所有.txt文件路径
sub_path_sum = []
for j in range(len(sub_catalogue_path)):
for k in range(len(sub_catalogue_file[j])):
(file_name, file_extension) = os.path.splitext(sub_catalogue_file[j][k])
if file_extension == '.txt':
sub_path_sum.append(sub_catalogue_path[j] + '\\' + sub_catalogue_file[j][k])
return sub_path_sum
#函数形参为路径列表中每一个元素
def find_start_keys(sub_index, start_keys):
#默认方式打开文件
f = open(sub_index)
flag = False
count_f = 1#文件行数计算
count_line = []#存储出现关键字的对应行
location_start_keys = []
for each_line in f:
if start_keys in each_line:
flag = True
count_line.append(count_f)
location_start_keys.append(location_keys(start_keys, each_line))
count_f += 1
if flag == True:
print('===========================================')
print('在文件[%s]中找到关键字[%s]' % (sub_index, start_keys))
#对相应出现的行以及位置进行显示
for i in range(len(count_line)):
print('关键字出现在第[%d]行,第%s个位置' % (count_line[i], str(location_start_keys[i])))
f.close()
#当用户选择打印信息时:
if choose == 'YES':
sub_path_sum = file_sum_path(start_catalogue)
for each in sub_path_sum:
find_start_keys(each, start_keys)
小结:
[1]在使用os模块的基础上,os.walk(top)返回值为一个元组,其中元组第一个元素和第三个元素拼接起来为文件对应路径
[2]字符串中查找对应字符所有下标位置的方法:
#以字符串str1为例子:
str1 = '1234875178341819'
location = []#存储位置
#令待查找字符为'1'
begin = 0
while str1.find('1', begin) != -1:
index = str1.find('1', begin)
location.append(index+1)
begin = index + 1