IO操作
一、os模块
作用:包含了操作系统的基本功能,提供了非常丰富的用来处理文件和目录的函数或方法。
1.属性
函数名 | 函数说明 |
name |
获取操作系统的类型 |
uname |
获取操作系统的信息(linux系统) |
curdir |
返回当前的目录 |
2.方法(./ 代表当前目录)
函数名 | 函数说明 |
getcwd() | 返回当前工作目录的绝对路径 |
listdir(path) | 以列表的形式返回当前工作目录下的所有文件和目录 |
mkdir(目录名) | 创建指定的目录(如果指定的目录已存在则报错) |
rmdir(目录名) | 删除指定的目录(如果指定的目录不存在则报错) |
rename(文件名,新名字) | 重命名 |
remove(文件名) | 移除文件 |
system(命令) | 运行命令shutdow -s -f |
3. os.path的常用方法
函数名 | 函数说明 |
abspath() | 返回指定目录的绝对路径 |
join() | 拼接路径,无论是否存在 |
split() | 拆分路径,无论是否存在 |
splitext() | 获取文件的扩展名,无论是否存在 |
getsize() | 获取文件大小,返回字节 |
isdir() | 判断是否为目录 |
isfile | 判断是否为文件 |
exists() | 判断文件或者目录是否存在 |
案列:(文件夹目录为A根目录,其中子目录为B,c,子文件:第一层.py;B文件夹里有子文件,c文件夹里也有子文件)
1.递归遍历目录
1 import os 2 3 4 def demo(path): 5 get_dir = os.listdir(path) 6 for f in get_dir: 7 new_path = os.path.join(path, f) # 拼凑完整路径, 绝对路径(path+文件名) 8 if os.path.isdir(new_path): # 判断是否是目录 9 demo(new_path) 10 if os.path.isfile(new_path): # 判断是否是文件 11 print(f) 12 13 14 path = r'E:\new_pychram\oldboy36\day13文件处理\A' 15 demo(path)
2.递归统计文件大小
1 import os 2 3 4 def demo(path): 5 file_size = 0 6 get_dir = os.listdir(path) 7 for f in get_dir: 8 new_path = os.path.join(path, f) # 拼凑完整路径, 绝对路径(path+文件名) 9 if os.path.isdir(new_path): # 判断是否是目录 10 file_size += demo(new_path) 11 12 if os.path.isfile(new_path): # 判断是否是文件 13 file_size += os.path.getsize(new_path) 14 return file_size 15 16 17 path = r'E:\new_pychram\oldboy36\day13文件处理\A' 18 print(demo(path))
3.递归获取一个目录下的所有py后缀的文件,并且可以动态输入的
1 import os 2 3 4 def get_suffix(path, new_fileList, suffix): 5 get_dir = os.listdir(path) 6 for f in get_dir: 7 new_path = os.path.join(path, f) 8 if os.path.isdir(new_path): 9 get_suffix(new_path, new_fileList, suffix) 10 11 if os.path.isfile(new_path): 12 file_suffix = new_path.split('.')[-1] 13 if file_suffix.upper() == suffix.upper(): 14 new_fileList.append(f) 15 16 17 def show_file(path, suffix='py'): 18 new_fileList = [] 19 get_suffix(path, new_fileList, suffix) 20 if not new_fileList: 21 print('您检索的文件的扩展名{}不存在'.format(suffix)) 22 return 23 print('您要检索的扩展名为{}的文件个数为{},分别是:'.format(suffix, len(new_fileList))) 24 for f in new_fileList: 25 print(f) 26 27 28 def continue_get_file(): 29 global mark 30 get_continue = input('是否继续检索(y/n):') 31 if get_continue == 'y': 32 mark = True 33 else: 34 mark = False 35 print('退出系统!') 36 37 38 mark = True 39 while mark: 40 path = input('请输入要检索的路径:') 41 suffix = input('请输入要检索的文件扩展名(默认py):') 42 if os.path.exists(path): 43 if suffix: 44 show_file(path, suffix) 45 continue_get_file() 46 else: 47 show_file(path) 48 continue_get_file() 49 else: 50 print('请输入正确的路径!')