您的位置:首页 > 编程语言 > Python开发

Python os模块基本使用

2019-03-02 18:08 267 查看

文章目录

说明

本文运行环境

  • macOS 10.13.6
  • python 3.7
  • jupyter 4.4.0

当前要操作的目录结构如下

UsersNo_notionDesktopdeeplearningos_1os_2demo.txtothers

os

什么是os
os是operating system的缩写,提供系统相关功能。可用于读写文件,操作路径等。

引入os模块

import os

打印当前路径

print(os.getcwd())

#output:
/Users/No_notion/Desktop/deeplearning/

切换路径
切换到路径os_1下

os.chdir('/Users/No_notion/Desktop/deeplearning/os_1')
print(os.getcwd())

#output:
/Users/No_notion/Desktop/deeplearning/os_1

打印所有路径
当前路径为空

os.listdir()

#output:
[]

创建路径

#在os_1目录下创建img/png目录
os.makedirs('img/png')
os.makedirs('img/jpg')

#切换到img目录
os.chdir('./img')

#打印当前文件夹所有目录
os.listdir()
#output:
['jpg','png']

删除路径

os.rmdir('jpg')

#或者使用os.removedirs('jpg'),但此种方法会删除所有中间目录,慎用

更改文件名
先切换到os_2目录下

os.rename('demo.txt','text.txt')
os.listdir()

#output:
['text.txt']

文件的字节数与修改时间

os.stat('test.txt')

#output:
os.stat_result(st_mode=33188, st_ino=4335074644, st_dev=16777220, st_nlink=1,
st_uid=501, st_gid=20, st_size=30,
st_atime=1551519320, st_mtime=1551519252, st_ctime=1551519320)

#只打印目标信息

#打印文件大小
os.stat('test.txt').st_size
#output:
30

#打印文件修改时间
os.stat('test.txt').st_mtime
#output:
1551519252

#将st_mtime转换成date
from datetime import datetime
datetime.fromtimestamp(1551519252)

#output:
datetime.datetime(2019, 3, 2, 17, 34, 12)

文件信息表

符号 意义
st_dev ID of device containing file
st_ino inode number
st_mode protection
st_nlink number of hard links
st_uid user ID of owner
st_gid group ID of owner
st_rdev device ID (if special file)
st_size total size, in bytes
st_blksize blocksize for file system I/O
st_blocks number of 512B blocks allocated
st_atime time of last access
st_mtime time of last modification
st_ctime time of last status change

遍历目录
遍历整个目录树

for dirpath,dirnames,filenames in os.walk('/Users/No_notion/Desktop/deeplearning/os_1'):
print('current dirpath {}'.format(dirpath))
print('current dirnames {}'.format(dirnames))
print('current filenames {}'.format(filenames))
#output:
从略

路径拼接

#此方法的好处,是自动在需要地方添加'/'
os.path.join(os.environ.get('HOME'),'test.txt')

#output:
'/Users/No_notion/text.txt'

获取路径最后一个斜杠后的部分

os.path.basename('/Users/No_notion/test.txt')
#output:
test.txt

获取路径的最后一个斜杠前的部分

os.path.dirname('/Users/No_notion/test.txt')
#output:
'/Users/liuhuangshuzz'

将路径返回目录,文件名元组
将路径切割为最后一个斜杠之前的路径和之后的路径

os.path.split('/Users/No_notion/test.txt')
#output:
('No_notion', 'test.txt')

判断是否为目录

os.path.isdir('/Users/No_notion/test.txt')

#output:
False

判断是否为文件

os.path.isfile('/Users/No_notion/test.txt')

#output:
True

切割文件扩展名

os.path.splitext('/Users/No_notion/test.txt')
#output:
('/Users/No_notion/test', '.txt')
1bb8b

相关链接

  1. Official Documentation
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: