Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
Third, the path processing
python inside the os module There are many ways we achieve through the code to create, delete, and change directories, specifically listed below:
1. memorize: os.path.dirname and os.path.join
2. The following methods can be (uses look for information)
magic variables: file and name
file : absolute path of all files
name : where the module (file) module name, (if, then the value of the program startup file __main__)
"""
通过文件的路径去打开文件
相对路径:相对当前的工作路径去定位文件位置
.:代表当前路径
..:代表上一级路径(父级路径)
绝对路径:相对于电脑的根目录来进行定位(windows下面就是根据盘符)
"""
# @time:2019/10/27 5:47
# @Author:coco
# @File:test_path.py
# @software:PyCharm
with open('py21_01day_01file.py','r',encoding='utf8') as f:
data=f.read()
print(data)
The result: Path not found error
# 相对路径
with open('./py23_01day_01file.py','r',encoding='utf8') as f:
data=f.read()
print(data)
The result: open the file, make py23_01day_01file.py this file in the directory day9 directory
# 绝对路径
with open('D:\Python_test\py23_class\py23_04day\zy_03day.py', 'r', encoding='utf8') as f:
data = f.read()
print(data)
operation result:
# @time:2019/10/27 6:17
# @Author:coco
# @File:os_path_test.py
# @software:PyCharm
import os
# dirname()可以获取文件的父级路径
f_path="D:\Python_test\py23_class\py23_04day\zy_03day.py"
res=os.path.dirname(f_path)
print("os.path.dirname使用(res):")
print(res)
# 魔法变量
# __file___:代表当前文件在电脑中的绝对路径
print("魔法变量__file__:")
print(__file__)
# os.path.dirname:获取路径的父级目录
res1=os.path.dirname(__file__)
print("获取父级目录(res1):")
print(os.path.dirname(res1))
# 获取项目目录的文件
res2=os.path.dirname(__file__)
base_dir=os.path.dirname(res2)
print("获取项目目录的文件(base_dir):")
print(base_dir)
# 在电脑中的绝对路径
f2=base_dir+'\\'+'py23_04day'+'\\'+'zy_03day.py'
print("在电脑中的绝对路径(f2):")
print(f2)
# os.path.join:做路径拼接
file_path=os.path.join(base_dir,'py23_04day','zy_03day.py')
print("os.path.join使用,利用拼接的方式(file_path):")
print(file_path)
operation result:
# @time:2019/10/27 6:42
# @Author:coco
# @File:os_path_other.py
# @software:PyCharm
"""
os模块
"""
import os
# 查看当前工作路径
print('查看当前工作路径:')
print(os.getcwd())
# 切换工作路径到父级路径
os.chdir('..')
print('切换工作路径到父级路径:')
print(os.getcwd())
# 又切换回来了
os.chdir('路径处理')
print('又切换工到原来的路径:')
print(os.getcwd())
# 获取当前工作目录下所有的文件和目录
print('获取当前工作目录下所有的文件和目录:')
print(os.listdir())
# 获取了当前文件下所有的文件
os.chdir('../../py23_02day')
print('获取了当前文件下所有的文件:')
print(os.listdir())
# 创建文件夹
# os.mkdir('python778')
# 删除文件夹
# os.rmdir('python666')
# 判断是否是文件
res=os.path.isfile('D:\Python_test\py23_class\py23_04day\zy_03day.py')
print(res)
# 判断是否是目录
res1=os.path.isdir('D:\Python_test\py23_class\py23_04day\zy_03day.py')
print(res1)
operation result: