文件、文件夹 相对绝对路径、项目根路径相关总结
获取目录的方法
os.getcwd()os.path.abspath(__file__)
# 这里以我的接口自动化框架目录为例
# 当前目录并不是指脚本所在的目录,而是所运行脚本的目录
print(f'返回当前脚本【运行的】工作目录: {os.getcwd()}')
# 返回当前脚本文件的完整路径
print(f'返回当前脚本文件的完整路径: {os.path.abspath(__file__)}')
root_dir = os.path.dirname(os.getcwd())
print(f'方法1:{root_dir}')
root_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
print(f'方法2:{root_dir}')
运行结果:

拼接目录之os.path.join()的用法
# 这里以我的接口自动化框架目录为例
root_dir = os.path.dirname(os.getcwd())
print(f'获取项目根目录 方法1:{root_dir}')
# 拼接目录的用法(获取根目录下的file路径)
file_dir = os.path.join(root_dir, "file")
print(f'获取file文件夹的路径:{file_dir}')
运行结果

os.path.join()函数 链接多个路径组件 需要注意:
如果最后一个组件为空,则生成的路径以一个’\’分隔符结尾

从后往前看,会从第一个以”/”开头的参数开始拼接,之前的参数全部丢弃;

正确的写法:

若出现”./”开头的参数,会从”./”开头的参数的前面参数全部保留;

在Windows系统下 路径可以是
D:\12-12\xx, 也可以是D:/12-12/xx。Linux系统用的是/分隔符,而Windows用的是\
以下是 不同情况 动图演示

python中‘/‘和‘\‘和‘\‘的区别
dir1=r'D:\n_test'
dir2='D:\\n_test'
dir3='D:/n_test'
这三个路径的写法是等价的
扩展:
列举常用的几个 os 函数
os. chdir(’目标目录’) 切换到目标目录os.listdir('path')path: 内容目录的路径。列出字符串目录下的所有文件,也可以不传path,默认为当前目录路径 。举例:os.listdir(os.getcwd())、os.listdir()os.mkdir('目录')创建目录os.remove('D:\\file\\1.txt')删除文件(只能删除指定文件,不能删除文件夹),文件不存在时会报错os.rmdir()只能删除空文件夹,很少用shutil.rmtree()递归删除,可删除文件夹及其下面的所有文件import shutil # path是文件或文件夹路径 shutil.rmtree('path')
os.path.exists('目录')判断目录是否存在os.path.split('文件或者目录')把最后的一个目录或者文件和前面的目录分开,返回一个tupleos.path.splitext('文件')把文件的后缀名和前面分开,返回一个tuple使用**
Os.path.Isfile检查文件是否存在并使用os.remove删除它**#importing the os Library import os #checking if file exist or not if(os.path.isfile("test.txt")): #os.remove() function to remove the file os.remove("demo.txt") #Printing the confirmation message of deletion print("File Deleted successfully") else: print("File does not exist") #Showing the message instead of throwig an error
Python程序删除具有特定扩展名的所有文件
import os from os import listdir my_path = 'C:\Python Pool\Test\' for file_name in listdir(my_path): # endswith用于检查文件是否以.txt扩展名结尾 if file_name.endswith('.txt'): # my_path + file_name是我们要删除的文件的完整路径 os.remove(my_path + file_name)
实战应用 :
import os.path
"""
测试时先运行main.py,然后在case100目录下执行pytest -n auto --tep-reports
"""
dir_name = "case100"
if not os.path.exists(dir_name):
os.mkdir(dir_name)
for i in range(100):
suffix = i + 1
# str.zfill(width) 方法返回指定长度(width)的字符串,原字符串右对齐,前面填充0。比如001、002、003
name = "test_" + str(suffix).zfill(3)
with open(os.path.join(dir_name, name + ".py"), "w") as f:
content = f"""import time
def test_{suffix}(login):
print("this is {suffix}")
time.sleep(0.5)
"""
f.write(content)