文件、文件夹 相对绝对路径、项目根路径相关总结

获取目录的方法

  1. os.getcwd()

  2. 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}')

运行结果:

image-20230109152430893

拼接目录之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}')

运行结果

image-20230109153236360

os.path.join()函数 链接多个路径组件 需要注意:

  1. 如果最后一个组件为空,则生成的路径以一个’\’分隔符结尾

image-20230109170219559

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

http://biji.51automate.cn/blogs/img/Snipaste_2023-01-12_18-15-41.png

正确的写法:

image-20230109172235936

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

    image-20230109172823296

  2. 在Windows系统下 路径可以是D:\12-12\xx, 也可以是D:/12-12/xx。Linux系统用的是 /分隔符,而Windows用的是 \

以下是 不同情况 动图演示

截图_20221215175906

python中‘/‘和‘\‘和‘\‘的区别

dir1=r'D:\n_test'

dir2='D:\\n_test'

dir3='D:/n_test'

这三个路径的写法是等价的

扩展:

列举常用的几个 os 函数

  1. os. chdir(’目标目录’) 切换到目标目录

  2. os.listdir('path') path: 内容目录的路径。列出字符串目录下的所有文件,也可以不传path,默认为当前目录路径 。举例:os.listdir(os.getcwd())os.listdir()

  3. os.mkdir('目录') 创建目录

  4. os.remove('D:\\file\\1.txt') 删除文件(只能删除指定文件,不能删除文件夹),文件不存在时会报错

  5. os.rmdir() 只能删除空文件夹 ,很少用

  6. shutil.rmtree() 递归删除,可删除文件夹及其下面的所有文件

    import shutil
    # path是文件或文件夹路径
    shutil.rmtree('path')
    
  7. os.path.exists('目录') 判断目录是否存在

  8. os.path.split('文件或者目录') 把最后的一个目录或者文件和前面的目录分开,返回一个tuple

  9. os.path.splitext('文件') 把文件的后缀名和前面分开,返回一个tuple

  10. 使用**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
    
  11. 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)