Python 之目录处理

目录处理 OS
目录处理
目录-->路径,文件夹 文件:txt

1. 新建和删除一个目录


import os #引入os目录
from xx import xx


os.mkdir("D:\\PycharmProjects\\RobotFramework\\vda_pakage\\Learning\\python9") #绝对路径

os.rmdir("python8") #相对路径

 

2. 获取目录 文件的路径 __file__指定的是当前的文件


print(os.path.realpath(__file__)) #返回绝对路径及该路径下当前的文件
print(os.getcwd()) #返回当前绝对路径


D:\PycharmProjects\RobotFramework\vda_pakage\Learning\class_07_02.py
D:\PycharmProjects\RobotFramework\vda_pakage\Learning

 

print(os.path.dirname(__file__)) #返回指定路径的目录
print(os.path.basename(__file__)) #返回当前工作的文件名


D:/PycharmProjects/RobotFramework/vda_pakage/Learning
class_07_02.py

 

3. 拼接路径以及拼接之后新建


path = "D:\\PycharmProjects\\RobotFramework\\vda_pakage\\Learning"
new_path = os.path.join(path, "python10")
print(new_path)

# D:\PycharmProjects\RobotFramework\vda_pakage\Learning\python10

拼接之后再去新建目录,只能新建一级,不能跨级

os.mkdir(new_path)


new_path_1 = os.path.join(path, "python8\\python9", "python10")
print(new_path_1)
os.mkdir(new_path_1) #D:\PycharmProjects\RobotFramework\vda_pakage\Learning\python8\python9\python10

 

4. 获取目录信息,判断目录的性质
print(os.listdir("D:\\PycharmProjects\\RobotFramework\\vda_pakage\\Learning"))
os.listdir返回的结果是列表类型的数据,返回给出的路径下的文件和目录
['class1.py', 'class_07_02.py', 'hm_0630.py', 'path.py', 'python10', 'python8', 'python9', 'task2_06_25.py', 'task3_06_27.py', 'task3_addition_06_27.py', 'task4_06_30_fresh.py', 'task4_06_30_middle.py', 'task4_06_30_primary.py', '__init__.py']

 

判断文件或是目录的性质,返回的数据是布尔类型(True/False)
print(os.path.isfile(__file__)) #True
print(os.path.isdir(__file__)) #False

 

5. 对文件路径进行切割split,返回两个值,数据类型为元组
print(os.getcwd())
print(os.path.split(os.getcwd()))


D:\PycharmProjects\RobotFramework\vda_pakage\Learning
('D:\\PycharmProjects\\RobotFramework\\vda_pakage', 'Learning')


print(os.path.split(os.path.realpath(__file__)))
('D:\\PycharmProjects\\RobotFramework\\vda_pakage\\Learning', 'class_07_02.py')

 

#当前目录下创建3个文件夹,命名为test0,test1,test2
for i in range(3):
os.mkdir('test'+str(i))

posted @ 2018-07-11 09:55  薏米*  阅读(187)  评论(0编辑  收藏  举报