-
路径的拼接
import os
path = os.path.join("db", 'root', "a.txt")
print(path) -
上级目录
import os
path = os.path.join("db", 'root', "a.txt")
print(path) # db/root/a.txt
folder_path = os.path.dirname(path)
print(folder_path) # db/root -
项目中读取文件时,用绝对路径(file和abspath/join/dirname)
import os
base_dir = os.path.dirname(os.path.abspath(__file__))
file_path = os.path.join(base_dir, 'a1.txt')
print(file_path) # /Users/wupeiqi/PycharmProjects/jx/day06/a1.txt -
判断路径是否存在
v1 = os.path.exists("路径是否存在")
print(v1)# 注意:读取文件时,如果文件路径不存在报错。一般在读取文件时,要先判断是否在。
-
创建文件夹
os.makedirs("xxx/xxxx/xxxx")
import os
folder_path = "xxx/xxxx/xxxx"
if not os.path.exists(folder_path):
os.makedirs(folder_path) -
判断是否是文件夹
v1 = os.path.isdir(file_path)
print(v1) -
删除文件和文件夹
import os
os.remove(file_path) # 删除文件import shutil
shutil.rmtree(db_path) # 删除文件夹 -
查看目录下的所有文件和文件夹(一级目录)
import os
base_dir = os.path.dirname(os.path.abspath(__file__))
db_path = os.path.join(base_dir, 'db')
for name in os.listdir(db_path):
file_path = os.path.join(db_path, name)
print(name)
print(file_path) -
查看目录下的文件和文件夹(多级目录)
import os
base_dir = os.path.dirname(os.path.abspath(__file__))
db_path = os.path.join(base_dir, 'db')
for in_path, folder_list, name_list in os.walk(db_path):
for name in name_list:
abs_path = os.path.join(in_path,name)
print(abs_path)
import os
base_dir = os.path.dirname(os.path.abspath(__file__))
db_path = os.path.join(base_dir, 'db')
for in_path, folder_list, name_list in os.walk(db_path):
for name in name_list:
if name.endswith('md'):
abs_path = os.path.join(in_path, name)
print(abs_path)