Python基础----os模块

目录

1.重命名文件

2.删除文件

3.创建单层目录

4.创建多级目录

5.删除目录

6.删除多级目录

7.获取当前所在目录

8.获取目录列表

 9.切换所在目录 chdir()

10.判断文件或文件夹是否存在

11.判断是否为文件

12.判断是否为目录

13.获取绝对路径

14.判断是否为绝对路径

15.获取路径中的最后部分

16.获取路径中的路径部分

17.将多个目录组织成路径返回

18.获取文件信息


使用os模块对文件进行一些相关操作

首先代码前都要导入os模块 

import os

1.重命名文件

os.rename(src,dst)

src:旧文件或目录名

dst:新文件或目录名

os.rename('file/c.txt','file/c2.txt')

 

os.rename('file2/c.txt','file/c3.txt')

                            

2.删除文件

 os.remove(path)

os.remove('file/c3.txt')

                           

如果用这个操作来删除目录,会报错

            

3.创建单层目录

os.mkdir()

os.mkdir('file1')

不可用来创建多层目录

4.创建多级目录

os.makedirs()

递归创建目录

解决报错,再次创建将原来的覆盖掉

5.删除目录

os.rmdir()

os.rmdir('file1')

不能删除多级目录,会报错

os.rmdir('file3')

6.删除多级目录

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

os.removedirs('file3/file1')

如果上一层目录不为空则停止删除文件

os.removedirs('file2/file2_1')

如果file04不为空则报错

os.removedirs('file2/file2_1')

 

7.获取当前所在目录

os.getcwd()

ret=os.getcwd()
print(ret)

8.获取目录列表

os.listdir(path) 返回的为列表

ret=os.listdir(os.getcwd())
print(ret)

 9.切换所在目录 chdir()

os.chdir(path)

改变当前脚本工作目录

print(os.getcwd())
os.chdir(os.getcwd()+'//file')
print(os.getcwd())

10.判断文件或文件夹是否存在

os.path.exits(path)

b=os.path.exists('file/a.txt')
print(b)

11.判断是否为文件

os.path.isfile()

判断所传路径是不是文件 ,是返回True ,不是返回False

bool=os.path.isfile('a.txt')
print(bool)

bool=os.path.isfile('demo4-seek.py')
print(bool)

12.判断是否为目录

os.path.isdir()

ret=os.path.isdir('file2')
print(ret)

ret=os.path.isdir('file2_1')
print(ret)

13.获取绝对路径

os.path.abspath()

abspath=os.path.abspath('file')
print(abspath)

14.判断是否为绝对路径

os.path.isabs()

ret=os.path.isabs(os.getcwd())
print(ret)

15.获取路径中的最后部分

os.path.basename()

ret=os.path.basename('file2/file2_1')
print(ret)

print(__file__)
ret=os.path.basename(__file__)
print(ret)

 

16.获取路径中的路径部分

os.path.dirname()

获取父目录部分(不管是文件还是文件夹)

print(os.getcwd())
ret=os.path.dirname(os.getcwd())

17.将多个目录组织成路径返回

os.path.join()

ret=os.path.join('aa','bb','cc')
print(ret)

18.获取文件信息

os.path.getatime()

返回path所指向的文件或者目录的最后访问时间

ret=os.path.getatime('demo4-seek.py') 
print(ret)

 

os.path.getctime()

查看文件创建时间

ret=os.path.getctime('demo4-seek.py') 
print(ret)

 

os.path.getmtime()

返回path所指向的文件或者目录的最后修改时间

ret=os.path.getmtime('demo4-seek.py') 
print(ret)

 

os.path.getsize()

查看文件的大小 

ret=os.path.getsize('file/a.txt')
print(ret)

猜你喜欢

转载自blog.csdn.net/weixin_44239385/article/details/86248641