Python对文件和目录进行操作的方法(file对象/os/os.path/shutil 模块)

作者:jingxian 时间:2022-08-25 05:19:38 

使用Python过程中,经常需要对文件和目录进行操作。所有file类/os/os.path/shutil模块时每个Python程序员必须学习的。

下面通过两段code来对其进行学习。

1. 学习 file对象

2. 学习os/os.path/shutil模块

1.file对象学习:

项目中需要从文件中读取配置参数,python可以从Json,xml等文件中读取数据,然后转换成Python的内容数据结构。

下面以Json文件为例,实现从Json文件中获取配置参数。

code运行环境:python27+eclipse+pydev
Json文件名字:config_file.json
Json文件path: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模块

在任何一个稍微大一点的项目中,少不了的需要对目录进行各种操作,

比如创建目录,删除目录,目录的合并等各种有关目录的操作。

下面以一段code为例,来实现对os/os.path/shutil模块的学习。

下面的code实现的是删除文件夹installation内的所有文件(里面有文件和文件夹),

注意:是删除文件夹installation里面所有的文件,并不删除installation这个文件夹。

代码如下:

code运行环境: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,os,shutil,os.path
0
投稿

猜你喜欢

  • 使用Python实现从各个子文件夹中复制指定文件的方法

    2023-11-09 12:04:05
  • 开启Django博客的RSS功能的实现方法

    2022-06-16 02:02:04
  • ASP在线转flv+缩略图

    2007-08-27 16:18:00
  • python+requests接口压力测试500次,查看响应时间的实例

    2021-09-29 08:27:56
  • python利用xlsxwriter模块 操作 Excel

    2023-02-11 00:43:02
  • python判断文件是否存在,不存在就创建一个的实例

    2022-04-29 02:28:55
  • Python实现钉钉/企业微信自动打卡的示例代码

    2022-02-18 21:54:02
  • 简单谈谈Python中的模块导入

    2021-02-24 20:28:17
  • Python实现的三层BP神经网络算法示例

    2021-05-16 19:21:05
  • 浅谈ACCESS数据库升迁SQLSERVER注意事项

    2007-08-11 13:44:00
  • Python3 使用map()批量的转换数据类型,如str转float的实现

    2023-07-15 10:35:03
  • 数据库Oracle数据的异地的自动备份

    2010-07-27 13:28:00
  • 解决pytorch下只打印tensor的数值不打印出device等信息的问题

    2023-04-20 18:25:52
  • Django+zTree构建组织架构树的方法

    2023-08-13 06:17:54
  • Pytorch中torchtext终极安装方法以及常见问题

    2023-03-15 11:59:09
  • python基础之while循环语句的使用

    2021-03-16 16:54:20
  • python得到单词模式的示例

    2021-04-22 08:25:48
  • Python3 Post登录并且保存cookie登录其他页面的方法

    2023-08-18 22:45:52
  • tensorflow 限制显存大小的实现

    2023-03-04 02:19:59
  • appium测试之APP元素定位及基本工具介绍

    2021-09-24 20:51:47
  • asp之家 网络编程 m.aspxhome.com