Python文件与目录操作实战:file对象及os/os.path/shutil模块详解

码头散步
码头散步
发布时间:2026-10-13| 2人浏览过
原创

本文详解Python中文件与目录的操作方法。通过file对象读取JSON配置参数,演示如何将数据转换为字典结构。深入解析os、os.path及shutil模块,涵盖listdir、join、isfile/isdir、remove及rmtree等核心API,展示如何安全删除文件夹内所有文件而不删除目录本身,帮助开发者掌握基础IO与路径处理技能。

在Python开发过程中,频繁涉及对文件和目录的管理。熟练掌握file类以及os、os.path和shutil模块,是每一位Python开发者必须掌握的基础技能。

接下来,我们将通过具体的代码示例来深入学习和实践这些知识点。

1. 掌握file对象的使用

2. 掌握os/os.path/shutil模块的应用

1. file对象学习:

在实际项目中,经常需要从文件中读取配置参数。Python支持从Json、xml等多种格式的文件中读取数据,并将其转换为Python内部的数据结构以便处理。

本文以Json文件为例,演示如何从Json文件中获取配置参数。

代码运行环境:python27+eclipse+pydev Json文件名:config_file.json Json文件路径:C:\temp\config_file.json

Json文件中的内容如下:

{"user":"Tom","username":"root_tom","password":"Jerryispig","ipaddr":"10.168.79.172"} {"user":"Jerry","username":"root_jerry","password":"Tomispig","ipaddr":"10.168.79.173"}

具体代码如下:

import json #use json file ,you must import json.  
  
def verify_file_class():  
  file_json=open(r'C:\temp\config_file.json','r') # open config_file.json file with 'r'  
  for each_line in file_json.readlines():     #read each line data  
    print each_line               # verify each line data by print each line data  
    
    each_line_dict = json.loads(each_line)    # each row of the data into the 'dict'type of python  
      
    print 'the type of the each_line_dict:{type}'.format(type=type(each_line_dict)) # verify whether is‘dict'type  
      
    print 'user is: {user}'.format(user=each_line_dict['user'])  
    print 'username is: {username}'.format(username=each_line_dict['username'])  
    print 'password is: {password}'.format(password=each_line_dict['password'])  
    print 'ipaddr is: {ipaddr} \n'.format(ipaddr=each_line_dict['ipaddr'])  
      
    #use username,password, ipaddr ( enjoy your programming ! )  
    
  file_json.close()  # don't forgot to close your open file before.  
  
if __name__ == '__main__':  
  verify_file_class() 

运行结果如下:

{"user":"Tom","username":"root_tom","password":"Jerryispig","ipaddr":"10.168.79.172"}  
the type of the each_line_dict:<type 'dict'>  
user is: Tom  
username is: root_tom  
password is: Jerryispig  
ipaddr is: 10.168.79.172   
  
{"user":"Jerry","username":"root_jerry","password":"Tomispig","ipaddr":"10.168.79.173"}  
the type of the each_line_dict:<type 'dict'>  
user is: Jerry  
username is: root_jerry  
password is: Tomispig  
ipaddr is: 10.168.79.173 

学习os/os.path/shutil模块

在任何一个规模稍大的项目中,不可避免地需要对目录执行各种操作。

例如创建目录、删除目录、合并目录路径等与目录相关的操作。

下面通过一段代码示例,来演示如何学习使用os/os.path/shutil模块。

下面的代码实现了删除文件夹installation内所有文件的功能(该文件夹内包含文件和子目录)。

注意:此操作仅删除文件夹installation内部的所有文件和子目录,并不删除installation这个文件夹本身。

代码如下:

代码运行环境:python27+eclipse+pydev

import os 
import shutil  
 
 
def empty_folder(dir): 
  try: 
    for each in os.listdir(dir): 
      path = os.path.join(dir,each) 
      if os.path.isfile(path): 
        os.remove(path) 
      elif os.path.isdir(path): 
        shutil.rmtree(path) 
    return 0 
  except Exception as e: 
    return 1 
 
 
if __name__ == '__main__': 
  dir_path=r'D:\installation' 
  empty_folder(dir_path) 

上述简短的几行代码中,包含了6个与os/os.path/shutil模块相关的API。分别是:

1. os.listdir(dir) 
2. os.path.join(dir, each) 
3. os.path.isfile(path) /os.path.isdir(path) 
4. os.remove(path) 
5. shutil.rmtree(path) 

下面分别对上述6个最常见的与目录操作相关的API进行简要学习。

1. os.listdir(dir)

该函数返回指定目录下的所有文件和目录名组成的列表。

也就是说,它返回一个列表,列表中的元素由指定目录下的所有文件和目录组成。

>>> import os 
>>> os.listdir(r'c:\\') 
['$Recycle.Bin', 'Documents and Settings', 'eclipse', 'hiberfil.sys', 'inetpub', 'Intel', 'logon_log.txt', 'MSOCache', 'pagefile.sys', 'PerfLogs'<span style="font-family: Arial, Helvetica, sans-serif;">]</span> 

2. os.path.join(dir, each)

用于连接目录路径与文件名或子目录名。

>>> import os 
>>> os.path.join(r'c:\doog',r's.txt') 
'c:\\doog\\s.txt' 
>>> os.path.join(r'c:\doog',r'file') 
'c:\\doog\\file' 

3. os.path.isfile(path) / os.path.isdir(path)

os.path.isfile(path) 用于判断path是否为文件,如果是文件返回True,否则返回False。

os.path.isdir(path) 用于判断path是否为目录,如果是目录返回True,否则返回False。

>>> import os 
>>> filepath=r'C:\Program Files (x86)\Google\Chrome\Application\VisualElementsManifest.xml' 
>>> os.path.isdir(filepath) 
False 
>>> os.path.isfile(filepath) 
True 

4. os.remove(path)

用于删除指定文件。无论文件是否为空,均可执行删除操作。

注意:该函数只能删除文件,不能删除目录,若尝试删除目录则会报错。

>>> import os 
>>> os.removedirs(r'c:\temp\david\book\python.txt') 

5. shutil.rmtree(path)

如果目录中包含文件和子目录,即一个目录中无论有多少子目录,这些子目录里面又包含多少文件和子目录。

若想删除这个上层目录(注意:是删除该目录及其包含的所有文件和子目录)。

该如何操作呢?

这时就需要使用shutil模块中的rmtree()函数。

>>> import shutil 
>>> shutil.rmtree(r'C:\no1') 

以上关于Python对文件和目录进行操作的方法(file对象/os/os.path/shutil 模块)的全部内容就是小编分享给大家的,希望能给大家一个参考,也希望大家多多支持本站。

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

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 算法库。