python文件os模块操作归纳

1、文件重命名
第一个参数是原文件名,第二个参数是新文件名。

os.rename('file/aaa.txt','aa.txt')

2、删除文件

os.remove('a.txt')

3、创建一层目录

os.mkdir('file02')

4、创建多层目录

os.makedirs('file04/file05/file06')
os.makedirs('file04/file05,exist_ok=True')#递归常见目录 如果已存在拨错 exist_ok=True 不报错

5、删除一层空目录
os.rmdir(‘file01’)
6、删除多个空目录
os.makedirs(‘file04/file05/file06’)
os.makedirs(‘file04/file05/file06’)
7、getcwd()获取当前路径
ret=os.getcwd()
print(ret)
8、ret=os.listdir(os.getcwd())
print(ret)
9、os.chdir(os.getcwd()+’/file’)
print(os.getcwd())
10、判断文件或者文件夹是否存在
ret=os.path.exists(‘aa.txt’)
print(ret)#True或者 Flase
11、判断是否为文件
ret=os.path.isfile(‘aa.txt’)
print(ret)
12、判断是否为目录
ret=os.path.isdir(‘aa.txt’)
print(ret)
13、获取绝对路径
ret=os.path.cbspath(‘file’)
print(ret)
14、判断是否是绝对路径
ret1=os.path.abshath(‘file’)
ret1=os.getcwd()
print(ret1)
ret=os.path.isabs(ret1)
print(ret)
15、获取路径中的最后部分
ret=os.path.basename(‘file04/file05/a’)
print(ret)
16、获取路径中的路径部分
print(os.getcwd())
ret=os.path.dirname(os.getcwd())
print(ret)
17、将多个目录组成路径返回
ret=os.path.join(‘aa’,‘bb’,‘cc’)
print(ret)
18、
(1)、getatime()返回path所指向的文件或者目录的最后访问时间戳
(2)、getctime()查看文件创建时间戳
(3)、getmtime()返回path所指向的文件或者目录的最后修改时间戳
(4)、getsize()查看文件的大小

猜你喜欢

转载自blog.csdn.net/qq_44240254/article/details/86258921