python中os模块

Python的os模块包含普遍的操作系统功能。如果希望程序能够与平台无关,这个模块是尤为重要。可以处理文件和目录这些我们日常手动需要做的操作

C:\\Python25\\abc.txt
:
目录:C:\\Python25
文件名:abc
扩展名:.txt

OS模块中常用属性和函数:

1、os.getcwd()

查看当前所在目录(路径),即当前Python脚本工作的目录路径。

2、os.listdir()

返回指定目录下的所有文件和目录名。

>>> os.listdir(os.getcwd())
['Django', 'DLLs', 'Doc', 'include', 'Lib', 'libs', 'LICENSE.txt', 'MySQL-python-wininst.log', 'NEWS.txt', 'PIL-wininst.log', 'python.exe', 'pythonw.exe', 'README.txt', 'RemoveMySQL-python.exe', 'RemovePIL.exe', 'Removesetuptools.exe', 'Scripts', 'setuptools-wininst.log', 'tcl', 'Tools', 'w9xpopen.exe']

3、os.remove()

删除文件,不能删除文件夹;

>>> import os
>>> print(os.listdir('/test'))
['123', 'hello.txt', '.file', 'qwe']
>>> os.remove('/test/.file')
>>> print(os.listdir('/test'))
['123', 'hello.txt', 'qwe']
>>> os.remove('/test')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IsADirectoryError: [Errno 21] Is a directory: '/test'

4、os.system()

 运行shell命令,直接显示(相当于启动一个全新的shell,然后去执行那条命令,命令执行完成过后,shell直接退出);

>>> import os
>>> print(os.system('ls /test/'))    #调用系统命令
123  hello.txt	qwe
0
 
[root@server-7 test]# ls
123  hello.txt  qwe

5、os.path.split(path)

将path分割成目录和文件名二元组返回;

>>> import os
>>> print(os.path.split('/test/123/abc'))
('/test/123', 'abc')

6、os.path.splitext():分离文件名与扩展名

>>> os.path.splitext('a.txt')
('a', '.txt')

7、os.path.exists(path)

判断路径是否存在,如果path存在,返回True;如果不存在,返回Flase;

>>> import os
>>> print(os.path.exists('/test/123/abc'))
True

8、os.path.join(path1,[path2],[path3])

将路径和文件名分为一个列表中的两个元素,将它们拼起来,若其中有绝对路径,则之前的path将会被删除.;

>>> import os
>>> print(os.path.join('/test/','hello.txt'))
/test/hello.txt
>>> print(os.path.join('/test/123','hello.txt'))
/test/123/hello.txt

9、os.path.isfile()和os.path.isdir()函数分别检验给出的路径是一个文件还是目录。

>>> os.path.isdir(os.getcwd())
True
>>> os.path.isfile('a.txt')
False

10、os.path.exists()函数用来检验给出的路径是否真的存在

>>> os.path.exists('C:\\Python25\\abc.txt')
False
>>> os.path.exists('C:\\Python25')
True

11、os.makedirs() 生成一个多层递归目录

>>> import os
>>> os.makedirs('/home/test/xuan')

12、os.removedirs()

若目录为空,则删除,并递归到上一级目录,如若也为空,则删除,依次类推;

>>> import os
>>> os.removedirs('test/xuan')

13、os.mkdir()

创建一个目录;

>>> import os
>>> os.mkdir('test')        #只能创建一个目录
>>> os.mkdir('abc/123/xxx')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
FileNotFoundError: [Errno 2] No such file or directory: 'abc/123/xxx'

结果:
[root@server-7 home]# tree /home/
/home/
└── test

14、os.rmdir()

删除一个目录,若目录不为空则无法删除,报错;

>>> import os
>>> os.mkdir('test/abc')    #在test下创建一个abc;
>>> os.rmdir('test')        #无法删除test;
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
OSError: [Errno 39] Directory not empty: 'test'
>>> os.rmdir('test/abc')    #可以删除abc,因为abc目录下为空;
>>> 

15、os.listdir()

显示指定目录下,所有的文件和子目录,包括隐藏文件;

>>> import os
>>> dirs = os.listdir('/root')
>>> print(dirs)
['.bash_logout', '.bash_profile', '.cshrc', '.tcshrc', '.bashrc', 'full_stack', 'jf_blog', 'node-v8.9.4-linux-x64', '.bash_history', '.config', '.npm', '.pki', '.ssh', '.gitconfig', '.oracle_jre_usage', '.cache', '.python_history', 'douban', 'mysql57-community-release-el7-10.noarch.rpm', '.mysql_history', '.viminfo']

16、os.path.basename(path)

返回path最后的文件名(一个绝对路径只返回最后的文件名);

>>> import os
>>> print(os.path.basename('abc'))
abc
>>> print(os.path.basename('/test/123/abc'))
abc

17、os.path.dirname(path)

返回path的目录;

>>> import os
>>> print(os.path.dirname('/test/123/abc'))
/test/123

18、os.path.abspath(path)

返回path规范化的绝对路径;

>>> import os
>>> print(os.path.abspath('abc'))
/test/123/abc

19. os.walk(path)

返回以下三个结果:

  • root保存的就是当前遍历的文件夹的绝对路径
  • dirs保存当前文件夹下的所有子文件夹的名称(仅一层,孙子文件夹不包括
  • files保存当前文件夹下的所有文件的名称

例子:

文件夹目录树形图 :

在这里插入图片描述

文件夹具体内容如下:

在这里插入图片描述

import os

# 操作的文件夹路径
operate_path = r"/media/hewenyong/my_file/soft/jupyter_workspace/mm"

for root, dirs, files in os.walk(operate_path):
    print('root:',root)
    print('dirs:',dirs)
    print('files:',files)
    print('\n')


"""
*********************** 实验结果: *******************************
root: /media/hewenyong/my_file/soft/jupyter_workspace/mm
dirs: ['sss', 'hhh']
files: ['plaid_img_00006051.jpg', 'plaid_img_00006053.jpg', 'plaid_img_00006052.jpg']

root: /media/hewenyong/my_file/soft/jupyter_workspace/mm/sss
dirs: ['hewenyong']
files: ['cat.1.jpg', 'cat.0.jpg', 'cat.2.jpg']

root: /media/hewenyong/my_file/soft/jupyter_workspace/mm/sss/hewenyong
dirs: []
files: ['cat.93.jpg', 'cat.94.jpg', 'cat.92.jpg']

root: /media/hewenyong/my_file/soft/jupyter_workspace/mm/hhh
dirs: []
files: ['abstract_img_00028077.jpg', 'abstract_img_00028073.jpg', 'abstract_img_00028076.jpg', 'abstract_img_00028075.jpg', 'abstract_img_00028074.jpg']
"""

可以看到输出了三次root、dirs、files

这是因为1个根目录(mm)、加上2个子目录(hhh,sss)、一个孙子目录(hewenyong)一共4个目录,所以会遍历4次。

原文链接:

os.walk()的详细理解(秒懂)_一扣解千愁的博客-CSDN博客_os.walk模块详解

https://blog.csdn.net/weixin_44897792/article/details/95455084

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值