Python os模块实战:系统文件管理与目录遍历详解

阿橙
阿橙
发布时间:2026-10-14| 5人浏览过
原创

本文详细解析Python中os模块在系统管理中的核心应用,涵盖临时文件创建、目录切换与遍历、文件查找及批量操作。通过具体代码示例,演示如何利用glob和shutil实现文件的复制、移动、重命名及属性获取,适用于Windows环境下的自动化运维场景。

本文通过具体代码实例,介绍Python中os模块在系统管理任务中的应用方法,供读者参考学习。

临时文件处理

临时文件处理

获取临时目录与创建临时文件


import tempfile 
tempfile.gettempdir()
#'C:\\Users\\ADMINI~1\\AppData\\Local\\Temp'

tempfile.mkstemp()
#(4, 'C:\\Users\\ADMINI~1\\AppData\\Local\\Temp\\tmp9zc5ipzr')

tempfile.mkdtemp()
#'C:\\Users\\ADMINI~1\\AppData\\Local\\Temp\\tmp94wxuh44'

操作系统命令执行

操作系统命令执行

目录切换与创建


import os
os.chdir(r'd:')
#切换到目录(r为转义字符)

os.listdir(r'd:')
#显示目录下的所有文件

os.makedirs(r'd:\1\1')
#创建路径的所有文件

os.mkdir(r'd:\1')
#创建文件

文件查找功能

文件查找功能

使用glob进行模式匹配


import glob
glob.glob('d:*.txt')
#目录下的txt文件
glob.glob('d:*n.txt')
#目录下的以n.txt结尾的文件

目录遍历操作

目录遍历操作

使用os.walk遍历目录树


import re,os,os.path 

def run(top):
 for(dirname,subdirs,files) in os.walk(top):
 print("["+dirname+"]")
 for fname in files:
  print(os.path.join(dirname,fname))
if __name__=='__main__':
 run(r'd:\1')

系统管理综合应用示例

调用相关函数时需注意以下两点关键事项

第一,在执行其他操作前,必须先调用start()函数初始化环境。该环境需包含d:\ptest目录,且其下存在document、files和temp三个子目录,否则后续操作无法进行。第二,执行编号为(1)至(8)的具体任务时,只需调用test8()函数即可。

以下以解决第八个问题为例进行说明

初始化与任务调用


start()
test8()

假设目录结构为:d:\ptest下包含document、files和temp三个子目录。

环境初始化start()函数


import os,glob,shutil

def start():
 if os.path.exists(r'd:\ptest'):
 pass
 else:
 os.makedirs(r'd:\ptest\document')
 os.makedirs(r'd:\ptest\files')
 os.makedirs(r'd:\ptest\temp')

任务(1):将c:\windows目录下的所有.ini文件复制到document目录中。

复制.ini文件到document


def test1():
 file_lists=glob.glob('c:\windows\*.ini')
 for file in file_lists:
 shutil.copy(file,r'd:\ptest\document')

任务(2):将c:\windows目录下所有以字母'n'开头的文件复制到files目录中。

复制以'n'开头的文件到files


def test2():
 file_lists=glob.glob('c:\windows\*')
 #temp=[]#以'n'开头的所有文件
 for file in file_lists:
 files=file.replace('c:\windows\\','')
 if files.startswith('n'):
  shutil.copy(file,r'd:\ptest\files')
  #temp.append(file)

任务(3):检查files文件夹中是否存在notepad.exe文件。若存在,将其复制到temp目录并重命名为mypad.exe;若不存在,则提示未找到。

处理notepad.exe文件


def test3():
 if os.path.exists(r'd:\ptest\files\notepad.exe'):
 shutil.copy(r'd:\ptest\files\notepad.exe',r'd:\ptest\temp\mypad.exe')
 else:
 print("没有notepad.exe文件")

任务(4):检查document文件夹中是否存在win.ini文件。若存在,将其移动到temp目录;若不存在,则提示未找到。

移动win.ini文件


def test4():
 if os.path.exists(r'd:\ptest\document\win.ini'):
 shutil.move(r'd:\ptest\document\win.ini',r'd:\ptest\temp')
 else:
 print("没有win.ini文件")

任务(5):检查document文件夹中是否存在system.ini文件。若存在,将其以system.inf的名称复制到temp目录,随后删除原文件;若不存在,则提示未找到。

复制并删除system.ini文件


def test5():
 if os.path.exists(r'd:\ptest\document\system.ini'):
 #复制删除
 shutil.copy(r'd:\ptest\document\system.ini',r'd:\ptest\temp\system.inf')
 os.remove(r'd:\ptest\document\system.ini')
 
 #移动
 #shutil.move(r'd:\ptest\document\system.ini',r'd:\ptest\temp')
 else:
 print("没有system.ini文件")

任务(6):在document目录下新建名为mydir的文件夹,并将temp目录下的所有文件复制到mydir中。

创建mydir并复制temp文件


def test6():
 if os.path.exists(r'd:\ptest\document\mydir'):
 pass
 else:
 os.mkdir(r'd:\ptest\document\mydir')
 
 '''#遍历找出文件
 for (dirpath,dirnames,filenames)in os.walk(r'd:\ptest\document'):
 for file in filenames:
  print(os.path.join(dirpath,file))
 '''
 file_lists=glob.glob('d:\ptest\document\*')
 for file in file_lists:
 if os.path.isfile(file):
  if os.path.exists(file):
  print("文件已存在")
  else:
  shutil.copy(file,r'd:\ptest\document\mydir')

任务(7):将files目录及其内部所有文件整体复制为myfiles目录并置于mydir下,随后删除原有的files目录及其内部所有文件。

整体复制files目录为myfiles


def test7():
 #移动
 shutil.move(r'd:\ptest\files',r'd:\ptest\document\mydir\myfiles')
 
 '''#复制,删除
 file_lists=glob.glob(r'd:\ptest\files\*')
 print(file_lists)
 if os.path.exists(r'd:\ptest\document\mydir\myfiles'):
 pass
 else:
 os.mkdir(r'd:\ptest\document\mydir\myfiles')
 for file in file_lists:
 shutil.copy(file,r'd:\ptest\document\mydir\myfiles')
 os.remove(file)
 os.rmdir(r'd:\ptest\files')
 '''

任务(8):定位当前notepad.exe文件所在路径,输出其创建时间、最近访问时间和最近修改时间,并显示文件大小。

查找文件并获取属性信息


def find(top,name):  #find与next_find形成一个轮回,只有发现文件,或文件夹为空时跳出
 for (dirpath,dirnames,filenames) in os.walk(top):
 for file in filenames:
  if file==name:
  return os.path.join(dirpath,file)
 for dirs in dirnames:
  if dirs==name:
  return os.path.join(dirpath,dirs)
 #说明上述文件和目录中无查找内容,将目录列表发给next_find函数
 next_find(dirnames,top,name)
 
def next_find(dirnames,top,name):
 for temp in dirnames:
  #目录为空时跳出
  if not temp :
  break
  #更改遍历目录
  top=os.path.join(top,temp)
  #print(top)
  
  find(top,name)
import time
def test8():
 #将时间转换为时间参数
 geta=time.gmtime(os.path.getatime(find(r'd:\ptest','win.ini')))
 getm=time.gmtime(os.path.getmtime(find(r'd:\ptest','win.ini')))
 getc=time.gmtime(os.path.getctime(find(r'd:\ptest','win.ini')))
 #将时间参数转换为标准时间
 print("最近访问时间",time.strftime('%c',geta))
 print("最近修改时间",time.strftime('%c',getm))
 print("创建时间",time.strftime('%c',getc))
 print('大小%.3f'%(os.stat(find(r'd:\ptest','win.ini')).st_size/1024),'kB')

以上内容为本文的全部介绍,希望对读者的学习有所帮助,欢迎继续关注本站获取更多信息。

免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。

Python 相关产品和应用

全部下载
Selenium

Selenium

4.51.0 · Windows

用于浏览器自动化和 Web 测试的 Python 工具。

scikit-learn

scikit-learn

1.9.1 · Windows

常用 Python 机器学习算法与模型评估工具库。

Black

Black

26.10.1 · Windows

强调一致性的 Python 自动代码格式化工具。

Ruff

Ruff

0.17.1 · macOS

由 Rust 编写的高速 Python 代码检查和格式化工具。

pytest

pytest

9.1.1 · Windows

简洁而强大的 Python 自动化测试框架。

FastAPI

FastAPI

0.146.0 · Windows

高性能 Python API 框架,支持类型提示和自动接口文档。

Flask

Flask

3.1.3 · Windows

轻量灵活的 Python Web 应用框架。

Django

Django

6.1.2 · Windows

成熟的 Python Web 框架,适合构建内容站点和业务系统。

Spyder

Spyder

6.1.7 · Windows

面向科学计算与数据分析的 Python 集成开发环境。

SciPy

SciPy

1.18.1 · Windows

面向科学、工程和技术计算的 Python 算法库。