python中的目录_Python中的目录操作,之

@所有的目录操作都在os包里面:import os

@获取帮助信息:dir(os)

以下罗列了os模块常用函数

函数

说明

os.getcwd()

查看当前目录

os.listdir()

查看当前目录的子目录

os.chdir(path)

切换到某个目录

os.chdir(path)

切换目录

os.mkdir(path)

新建一个目录

os.makedirs(path)

新建多级目录

os.rmdir(path)

删除单级目录

os.removedirs(path)

删除多级目录

os.rename(src, dst)

重命名目录/文件

os.path.dirname

获取目录名

os.path.basename

获取文件名

os.path.splitext(path)

分离文件名和文件拓展名

os.path.exists(path)

判断文件是否存在

os.path.isdir(path)

判断是否为目录

os.path.isfile(path)

判断是否为文件

os.walk(top, topdown=True, οnerrοr=None, followlinks=False)

以递归的方式遍历目录和文件

1、查看当前目录:os.getcwd()

F:\blog>python

Python 3.6.5 (v3.6.5:f59c0932b4, Mar 28 2018, 17:00:18) [MSC v.1900 64 bit (AMD64)] on win32

Type "help", "copyright", "credits" or "license" for more information.

>>> import os

>>> os.getcwd()

'F:\\blog'

>>>

2、查看当前目录的子目录:os.listdir()

>>> os.listdir()

['python_file_dir']

>>>

3、切换目录:os.chdir(path)

3.1、切换到某个目录

以下是错误的操作,会报错

>>> os.chdir('F:\blog\python_file_dir')

Traceback (most recent call last):

File "", line 1, in

OSError: [WinError 123] 文件名、目录名或卷标语法不正确。: 'F:\x08log\\python_file_dir'

上面代码之所以报错,是因为path参数是文件路径,带有’\’,我们需要对其进行转义

转义方法1:把:’\’ 改成:’\\’

转义方法2:在路径前面加上:r

>>> os.chdir(r'F:\blog\python_file_dir')

>>> os.getcwd()

'F:\\blog\\python_file_dir'

>>>

3.2、切换到上一级目录

>>> os.chdir('..')

>>> os.getcwd()

'F:\\blog'

>>>

4、新建一个目录:os.mkdir(path)

>>> os.mkdir('test')

>>> os.listdir()

['test']

>>>

5、新建多级目录:os.makedirs(path)

>>> os.makedirs('a/b/c')

>>> os.listdir()

['a', 'test']

>>>

6、删除单级目录:os.rmdir(path)

如果目录不为空,会报错,文件夹test里面有文件时执行此操作:

>>> os.rmdir('test')

Traceback (most recent call last):

File "", line 1, in

OSError: [WinError 145] 目录不是空的。: 'test'

>>>

此函数只能删除空目录,文件夹test里面为空时执行此操作

>>> os.rmdir('test')

>>> os.listdir()

['a']

>>>

7、删除多级目录:os.removedirs(path)

如果目录不为空,会报错,文件夹a里面有b文件夹和b文件夹下面的c文件夹时,执行此操作

>>> os.removedirs('a')

Traceback (most recent call last):

File "", line 1, in

File "C:\Python36\lib\os.py", line 238, in removedirs

rmdir(name)

OSError: [WinError 145] 目录不是空的。: 'a'

>>>

此函数是递归删除目录,只能删除空目录,从最底层逐级往上删,若遇到当前目录不为空,则停止删除当前目录及往上的目录

>>> os.removedirs('a/b/c')

>>> os.listdir()

[]

>>>

要想强制删除文件夹(不管里面是否为空),可以使用shutil包里面的rmtree方法,其功能是强制删除目录,即:不管目录里面是否有文件,都被删除

8、重命名目录/文件:os.rename(src, dst)

src为需要重命名的目录/文件名,dst为新的目录或文件名

>>> os.listdir()

['test0']

>>> os.rename('test0','test')

>>> os.listdir()

['test']

>>>

【示例】

在F:\blog\python_file_dir目录下建立一个10级目录,每一级的目录名叫做:test1,test2…test10,每一级目录下面,新建两个文件,分别命名为文件1,文件2,文件1内容为当前目录名,文件2内容为:测试

import os

os.chdir(r'F:\blog\python_file_dir')

for i in range(1,11):

dirname = 'test'+str(i)

os.mkdir(dirname)

os.chdir(dirname)

with open('文件夹1.txt','w',encoding = 'utf-8') as fp:

fp.write(dirname)

with open('文件夹2.txt','w',encoding = 'utf-8') as fp:

fp.write('测试')

print('所有目录和文件创建成功!')

9、获取目录/文件名:os.path.dirname/os.path.basename

>>> file_path = r'F:\blog\python_file_dir\文件夹1\文件1.txt'

>>> os.path.dirname(file_path)

'F:\\blog\\python_file_dir\\文件夹1'

>>> os.path.basename(file_path)

'文件1.txt'

>>>

还可以使用:os.path.split方法,结合坐标来获取目录/文件名:

>>> file_path = r'F:\blog\python_file_dir\文件夹1\文件1.txt'

>>> os.path.split(file_path)[0]

'F:\\blog\\python_file_dir\\文件夹1'

>>> os.path.split(file_path)[1]

'文件1.txt'

>>>

10、分离文件名和文件拓展名:os.path.splitext(path)

>>> file_name = '文件1.txt'

>>> os.path.splitext(file_name)[0]

'文件1'

>>> os.path.splitext(file_name)[1]

'.txt'

>>>

11、判断文件是否存在:os.path.exists(path)

判断目录或文件是否存在,如果存在则返回True,否则返回False

>>> os.listdir()

['test', 'test1']

>>> os.path.exists('test')

True

>>> os.path.exists('testxx')

False

>>>

【示例】

判断文件是否存在,如果不存在,则创建

if not os.path.exists('testxx.txt'):

with open('testxx.txt','w',encoding = 'utf-8') as fp:

fp.write('测试\n')

12、判断是否为目录/文件:os.path.isdir(path)/os.path.isfile(path)

是则返回True,否则返回False

>>> os.listdir()

['test', 'test1', 'testxx.txt']

>>> os.path.isdir('test1')

True

>>> os.path.isfile('test')

False

>>>

【示例】

统计F:\blog\python_file_dir当前层级下面的文件有几个,目录有几个

import os

dir_path = r'F:\blog\python_file_dir'

file_count = 0

dir_count = 0

for i in os.listdir(dir_path):

if os.path.isfile(i):

file_count += 1

else:

dir_count += 1

print('总共有 {0} 个目录和 {1} 个文件'.format(dir_count,file_count))

13、以递归的方式遍历目录和文件:os.walk(top, topdown=True, οnerrοr=None, followlinks=False)

通过自上而下或自下而上遍历目录树来生成目录树中的文件名,生成一个3元组(dirpath、dirnames、filenames)

top:根目录

topdown:topdown为True或未指定时,则是自上而下进行遍历;topdown为False时,则是自下而上进行遍历

onerror:的默认值是“None”,表示忽略文件遍历时产生的错误

followlinks:是否遍历软连接(类似于windows中的快捷方式)

【示例】

统计F:\blog\python_file_dir\test1所有层级下面的文件有几个,目录有几个

import os

file_count = 0

dir_count = 0

for root,dirs,files in os.walk(r'F:\blog\python_file_dir'): #以递归的方式遍历目录和文件

print('当前遍历的目录是:',root)

for dir in dirs:

dir_count += 1

for file in files:

file_count += 1

print('总共有 {0} 个目录和 {1} 个文件'.format(dir_count,file_count))

以上列举了os模块较常用的函数,更多函数的应用可参考官方文档:

Python 标准库之os — 多种操作系统接口

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值