模块
模块是一个包含所有你定义的函数和变量的文件,其后缀是“.py”, 模块可以被别的程序所引入,以使用该模块中的函数等功能
1.OS模块(Operating System操作系统)
- 不同操作系统底层对于文件系统的访问工作原理不同,因此可能就要针对不同的系统来考虑使用哪些文件系统模块,就意味着当你的程序运行环境一旦发生改变,就要相应的去修改大量的代码
- Python是跨平台的语言,即同样的源代码在不同操作系统下使用什么模块,OS模块会帮你选择正确的模块并调用
os模块中关于文件/目录常用的函数使用方法
- 先把模块导入Python,这些函数才可使用
import os
os.getcwd()
'C:\\Users\\Xuyunfeng\\AppData\\Local\\Programs\\Python\\Python39'
os.chdir("G:\\")
os.getcwd()
os.listdir("G:\\")
os.mkdir("G:\\A")
os.mkdir("G:\\A\\B")
>>> os.mkdir("G:\\A\\B")
>>> os.mkdir("G:\\c\\B")
os.rmdir("G:/A/B")
应先删除文件,再删除目录
os.remove(("G:/A/B/test.txt")
os.system("cmd")
os.system("calc")
os.listdir(os.curdir)
os.path模块中关于路径常用的函数使用方法
os.path.basename("E:\\A\\B\\C\\sexy.avi")
os.path.join('A','B','C')
os.path.join('G:\\','A','B','C')
os.path.split('E:\\A\\SEXY.AVI')
os.path.splitext('E:\\A\\SEXY.AVI')
os.path.getatime('G:\\A\\test.txt')
time.gmtime(os.path.getatime('G:\\A\\test.txt'))
time.localtime(os.path.getatime('G:\\A\\test.txt'))
time.localtime(os.path.getmtime('G:\\A\\test.txt'))
>>> os.path.ismount('E:\\')
>>> os.path.ismount('E:\\A')
Task
0. 编写一个程序,统计当前目录下每个文件类型的文件数,程序实现如图
我的代码
import os
os.chdir("G:\\A")
os.getcwd()
files = os.listdir("G:\\A")
count_txt_ == 0
count_png_ == 0
count_py_ == 0
count_docx_ == 0
count_dir_ == 0
for each_file in files:
aftersplit = os.path.splitext('each_file')
if aftersplit[1] == '.txt':
count_txt_ += 1
elif aftersplit[1] == '.png':
count_png_ += 1
elif aftersplit[1] == '.py':
count_py_ += 1
elif aftersplit[1] == '.docx':
count_docx_ += 1
else:
count_dir_ += 1
print("该文件夹下共有类型为【.txt】的文件"+"count_txt_"+"个")
print("该文件夹下共有类型为【.png】的文件"+"count_png_"+"个")
print("该文件夹下共有类型为【.py】的文件"+"count_py_"+"个")
print("该文件夹下共有类型为【.docx】的文件"+"count_docx_"+"个")
print("该文件夹下共有类型为【文件夹】的文件"+"count_dir_"+"个")
小甲鱼代码
import os
all_files = os.listdir(os.curdir) # 使用os.curdir表示当前目录更标准
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]))
1. 编写一个程序,计算当前文件夹下所有文件的大小,程序实现如图:
import os
summary = dict()
files = os.listdir(os.curdir)
for each_file in files:
if os.path.isfile(each_file):
file_size = os.path.getsize(each_file)
summary[each_file] = file_size
for each_name in summary.keys():
print("%s 【%d Bytes】" %(each_name,summary[each_name]))
2.编写一个程序,用户输入文件名以及开始搜索的路径,搜索该文件是否存在。如遇到文件夹,则进入文件夹继续搜索,程序实现如图:
import os
def search_file(startdir,targetfile):
os.chdir(startdir)
for each_file in os.listdir(os.curdir):
if each_file == targetfile:
print(os.getcwd() + os.sep + each_file)# 使用os.sep是程序更标准
if os.path.isdir(each_file):
search_file(each_file,targetfile)#递归调用
os.chdir(os.pardir) #递归调用后切记切回上一级目录,对上级目录的其他文件进行判断
startdir = input("请输入待查找的初始目录:")
targetfile = input("请输入需要查找的目标文件:")
search_file(startdir,targetfile)