Python OS常用函数总结

1.属性类

os.sep

返回操作系统的路径分隔符

In :os.sep
Out: '\\'

os.linesep

返回操作系统的终止符.Windows使用’/r/n’,Linux/Unix是’/n’.

In :os.linesep
Out: '\r\n'

os.name

返回目前操作系统的平台名,Windows是’nt’,Linux/Unix是’posix’

In :os.name
Out: 'nt'

E盘

这里写图片描述

2.方法类

os.getcwd()

返回当前工作目录的绝对路径

In :os.getcwd()
Out: 'E:\\Test'

os.getenv(key)

获取名为key的环境变量名.key是字符串

os.putenv(name,value)

添加名为name,值为字符串value的环境变量

os.listdir(path)

返回path路径下的所有文件名和目录名(列表)

In :os.listdir("E:\\Test")
Out: 
['test.py',
 'testdir1',
 'testdir2',
 'testdoc.docx',
 'testtxt.txt',
 'testzip.zip']

os.remove(path)

删除指定路径下的文件名

In :os.listdir("E:\\Test")
Out: ['test.py', 'testdir1', 'testdir2', 'testdoc.docx', 'testtxt.txt']

os.system(command)

command是一个字符串,利用系统shell去执行command命令

In :os.system("systeminfo")
Out: 0

这里写图片描述

os.path.split(path)

返回一个文件的目录名和文件名,返回的是一个元组

In :os.path.split("E:\\Test\\testtxt.txt")
Out: ('E:\\Test', 'testtxt.txt')

os.path.isflie(path)

如果path是文件,则返回True,否则返回False

In :os.path.isfile("E:\\Test\\testdir1")
Out: False
In :os.path.isfile("E:\\Test\\testtxt.txt")
Out: True

os.path.isdir(path)

如果path是目录,则返回True,否则返回False

In :os.path.isdir("E:\\Test\\testdir1")
Out: True

os.path.exists(path)

如果path存在的话,返回True,否则返回False

In :os.path.exists("E:\\Test\\testdir3")
Out: False
In :os.path.exists("E:\\Test\\testdir2")
Out: True

os.chdir(dir)

把工作目录改到dir下

os.getsize(filename)

返回文件fliename的大小

In :os.path.getsize("E:\\Test\\testtxt.txt")
Out: 0

os.abspath(path)

In :os.path.abspath("testtxt.txt")
Out: 'E:\\Test\\testtxt.txt'

os.path.splitext(filename)

分离文件的文件名和拓展名,拓展名前有.返回的是一个元组

In :os.path.splitext("testtxt.txt")
Out: ('testtxt', '.txt')

os.path.join()

根据系统连接文件名

os.path.join(“home”, "me", "mywork")

在Linux系统上会返回

“home/me/mywork"

在Windows系统上会返回

"home\\me\\mywork"

os.path.basename(path)

返回路径中的文件名

In :os.path.basename("E://testtxt.txt")
Out: 'testtxt.txt'
In :os.path.basename("E://Test//testdir1")
Out: 'testdir1'

os.path.dirname(path)

返回路径中的目录,注意下面两个例子的区别

In :os.path.dirname("E://Test//testtxt.txt")
Out: 'E://Test'
In :os.path.dirname("E://Test//testdir1")
Out: 'E://Test'
  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值