os常用操作
import os os.system ('notepad.exe') # 打开记事本 # 直接调用可执行文件 os.startfile('C:\Program Files (x86)\EVCapture\EVCapture.exe') print(os.listdir('../test prac_new')) # 显示文件夹中所有文件 os.mkdir('newfile') # 创建文件夹 os.makedirs('a/b/v') # 创建多级目录 os.removedirs('a/b/v') # 移除多级目录
os.path常用操作
import os.path print(os.path.abspath("test_new.py")) # 显示所在文件目录 print(os.path.exists('os.py'), os.path.exists('111.py')) # 查看文件是否存在,存在输出True,不存在输出False注意:只能查询同一文件夹中的文件
print(os.path.split()) # 文件名、文件路径拆分 print(os.path.basename('D:\QC\测试\学习\python\Python test\os\test_new.py')) # 提取文件名称 print(os.path.dirname('D:\QC\测试\学习\python\Python test\os\test_new.py')) # 提取目录 print(os.path.isdir('D:\QC\测试\学习\python\Python test\os\test_new.py')) # 是否存在
案例一:
输出指定文件夹下的所有以py结尾的文件
import os path = os.getcwd() # 获取当前目录 file = os.listdir(path) # 获取当前目录下所有文件 for filename in file: # 遍历所有文件 if filename.endswith('.py'): # 如果以py结尾,则输出 print(filename)
案例二:
os.walk()返回的是一个元组(dirpath, dirname, filename)
- dirpath 当前遍历文件本身地址
- dirname 是该文件夹中所有的目录的名字
- filename 是该文件夹中所有的文件
输出文件夹中所有文件(包括子文件夹)
import os path = os.getcwd() # 获取当前文件 file = os.walk(path) # 返回为元组 for dirpath, dirname, filename in file: print(dirpath) print(dirname) print(filename)
结果:
输出路径+文件夹
import os path = os.getcwd() # 获取当前文件 file = os.walk(path) # 返回为元组 for dirpath, dirname, filename in file: for dir in dirname: # 输出路径+文件夹名 print(os.path.join(dirpath,dir)) for file in filename: # 路径+文件名 print(os.path.join(dirpath,file))
结果:
总结:
1)先确定文件位置(若定位当前文件则使用getcwd())
2) 获取文件夹中指定文件信息(listdir()、walk())
3)for循环遍历所有文件+if条件输出文件信息