文章目录
- 前言
- 一、文件和目录操作
- 1.1 基础路径操作
- 1.2 目录遍历和文件列表
- 1.3 目录创建和删除
- 1.4 文件操作
- 二、路径信息检查
前言
Python的 os 模块提供了丰富的操作系统交互功能。
一、文件和目录操作
1.1 基础路径操作
# -*- coding: UTF-8 -*-importos Input=r"E:\Data\city.shp"current_dir=os.getcwd()print(current_dir)# 获取当前工作目录 E:\Dataos.chdir(r"E:\XML")print(os.getcwd())# 改变当前工作目录 E:\XMLfull_path=os.path.join(r"E:\Data",'file.txt')print(full_path)# 路径拼接(推荐使用) E:\Data\file.txtname=os.path.basename(Input)print(name)#要获取文件 city.shppath=os.path.dirname(Input)print(path)#要获取文件路径 E:\Databasename=os.path.basename(Input).rstrip(os.path.splitext(Input)[1])print(basename)#要获取文件名 cityex=os.path.splitext(Input)[1].lstrip(".")print(ex)#要获取文件扩展名 shp1.2 目录遍历和文件列表
python# 改变当前工作目录os.chdir(r"E:\XML")# 列出目录内容files=os.listdir('.')# 返回列表forfileinfiles:print(file)#递归遍历目录(常用)# 改变当前工作目录os.chdir(r"E:\XML")#使用 os.walk 递归遍历目录#walk 返回三元组:(当前路径, 子目录列表, 文件列表)forroot,dirs,filesinos.walk("."):print("当前目录: {}".format(root))print(" 子目录: {}".format(dirs))print(" 文件: {}".format(files))forfileinfiles:full_path=os.path.join(root,file)print("{}".format(full_path))1.3 目录创建和删除
python# 改变当前工作目录os.chdir(r"E:\XML")# 创建单个目录os.mkdir('new_dir')# 递归创建多级目录os.makedirs('a1/b1/c1',True)# True避免目录已存在时报错# 删除目录shutil.rmtree(r'E:\XML\a1')1.4 文件操作
python# 改变当前工作目录os.chdir(r"E:\XML")# 重命名/移动文件os.rename('old.txt',r"E:\XML\Data\new.txt")# 删除文件os.remove(r"E:\XML\Data\new.txt")# 检查文件/目录是否存在ifos.path.exists('old.txt'):print("文件存在")# 获取文件大小(字节)size=os.path.getsize('old.txt')print(size)# 获取修改时间(时间戳)mtime=os.path.getmtime('old.txt')print(mtime)二、路径信息检查
python# 改变当前工作目录os.chdir(r"E:\XML")# 检查类型print(os.getcwd())# 是否为文件print(os.path.isfile('old.txt'))# 是否为目录print(os.path.isdir('Data'))