python基础指令函数

一、os

1 os.getcwd() 获取当前工作目录,即当前python脚本工作的目录路径
2 os.chdir(“dirname”) 改变当前脚本工作目录;相当于shell下cd
3 os.curdir 返回当前目录: (’.’)
4 os.pardir 获取当前目录的父目录字符串名:(’…’)
5 os.makedirs(‘dirname1/dirname2’) 可生成多层递归目录
6 os.removedirs(‘dirname1’) 若目录为空,则删除,并递归到上一级目录,如若也为空,则删除,依此类推
7 os.mkdir(‘dirname’) 生成单级目录;相当于shell中mkdir dirname
8 os.rmdir(‘dirname’) 删除单级空目录,若目录不为空则无法删除,报错;相当于shell中rmdir dirname
9 os.listdir(‘dirname’) 列出指定目录下的所有文件和子目录,包括隐藏文件,并以列表方式打印
10 os.remove() 删除一个文件
11 os.rename(“oldname”,“newname”) 重命名文件/目录
12 os.stat(‘path/filename’) 获取文件/目录信息
13 os.sep 输出操作系统特定的路径分隔符,win下为"\",Linux下为"/"
14 os.linesep 输出当前平台使用的行终止符,win下为"\t\n",Linux下为"\n"
15 os.pathsep 输出用于分割文件路径的字符串 win下为;,Linux下为:
16 os.name 输出字符串指示当前使用平台。win->‘nt’; Linux->‘posix’
17 os.system(“bash command”) 运行shell命令,直接显示
18 os.environ 获取系统环境变量

os 模块在运维工作中是很常用的一个模块。通过os模块调用系统命令。os模块可以跨平台使用。
在 import os的时候,建议使用import os而非from os import *。这样可以避免os.open()不会覆盖内置函数open().

os.name()
判断系统类型

import os
print os.name
#linux和Unix系统会返回`posix`
#windows 系统会返回`nt`

os.system()
执行系统命令的模块,返回命令执行的状态码,开启一个子shell执行命令

import os
cmd = 'ifconfig'
retval = os.system(cmd)
print retval

#结果为 0
#表示命令执行成功,否则为失败

os.popen()
popen也是去执行一个命令,不过相比system(cmd),os.popen(command [, mode='r' [, bufsize]]),参数更多,而且是开启一个管道去执行。
•cmd - 执行的命令
•mode - 模式权限可以是’r’(默认)或’w’
•buffering - 0意味着无缓冲;1意味着行缓冲;其它正值表示使用参数大小的缓冲(大概值,以字节为单位)。负的bufsize意味着使用系统的默认值,一般来说,对于tty设备,它是行缓冲;对于其它文件,它是全缓冲。如果没有改参数,使用系统的默认值。

import os
cmd = 'mkdir nwdir'
a = os.popen(cmd)
print a
print type(a)

#返回结果
#<os._wrap_close object at 0x105af0860>
#<class ‘os._wrap_close’>

os.listdir(path)
打印指定目录的文件,返回一个列表

import os
a = os.listdir('/tmp')
print a

os.getcwd()
返回当前绝对路径,返回类型为str

import os
a = os.getcwd()
print a

os.chdir(path)
改变当前路径

import os
print os.getcwd()
os.chdir(/tmp/aaa)
print os.getcwd()

os.mkdir()
mkdir(path [, mode=0755])
默认权限是0755
如果目录已存在,会异常OSError

os.remove(path)
删除文件,只能删除文件

os.rmdir(path)
删除目录,只能删除目录

os.path
该模块主要是针对路径的操作。

os.path.abspath(path)
返回绝对路径,主要有引号

import os
print os.path.abspath('.')
#结果
D:\Python\project

os.path.basename(path)
返回文件名,类似linux 中的basename命令

import os
print os.path.basename('D:\Python\project')
#结果
project

os.path.dirname(path)
返回文件路径,不包含文件名,类似linux中的dirname命令

import os
print os.path.dirname('D:\Python\project')
#结果
D:\Python

os.path.exists(path)
判断路径是否存在,存在返回True,不存在返回False

a = 'D:\Python\project11111'
print os.path.exists(a)

#结果
False

类似这种:
在这里插入图片描述

二、python中的finally用法

无论try语句中是否抛出异常,finally中的语句一定会被执行。我们来看下面的例子:

try:
   f = open("/tmp/output", "w")
   f.write("hello")
   #raise Exception("something wrong")
finally:
   print("closing file")
   f.close()

不论try中写文件的过程中是否有异常,finally中关闭文件的操作一定会执行。由于finally的这个特性,finally经常被用来做一些清理工作。

def func1():
   try:
       return 1
   finally:
       return 2
def func2():
   try:
       raise ValueError()
   except:
       return 1
   finally:
       return 3
print(func1())
print(func2())

这个例子中 func1() 和 func2() 返回什么呢?

答案是 func1() 返回2, func2() 返回3。为什么是这样的呢?我们先来看一段Python官网上对于finally的解释:

A finally clause is always executed before leaving the try statement, whether an exception has occurred or not. When an exception has occurred in the try clause and has not been handled by an except clause (or it has occurred in a except or else clause), it is re-raised after the finally clause has been executed. The finally clause is also executed “on the way out” when any other clause of the try statement is left via a break, continue or return statement.

重点部分用粗体标出了,翻成中文就是try块中包含break、continue或者return语句的,在离开try块之前,finally中的语句也会被执行。
所以在上面的例子中,func1() 中,在try块return之前,会执行finally中的语句,try中的return被忽略了,最终返回的值是finally中return的值。func2() 中,try块中抛出异常,被except捕获,在except块return之前,执行finally中的语句,except中的return被忽略,最终返回的值是finally中return的值。
我们在上面的例子中加入print语句,可以更清楚地看到过程

def func1():
   try:
       print 'in func1 try: try statement, will return 1'
       return 1
   finally:
       print 'in func1 finally: try statement, will return 2'
       return 2
def func2():
   try:
       print 'in func2 try: raise error'
       raise ValueError()
   except:
       print 'in func2 except: caught error, will return 1!'
       return 1
   finally:
       print 'in func2 finally: will return 3'
       return 3
print func1()
print func2()

上面的代码输出
在这里插入图片描述
我们对上面的func2做一些修改,如下
在这里插入图片描述
输出如下

in func2 try: raise error
in func2 finally: will return 3
3

try中抛出的异常是ValueError类型的,而except中定位的是IndexError类型的,try中抛出的异常没有被捕获到,所以except中的语句没有被执行,但不论异常有没有被捕获,finally还是会执行,最终函数返回了finally中的返回值3。
这里还可以看到另外一个问题。try中抛出的异常没有被捕获到,按理说当finally执行完毕后,应该被再次抛出,但finally里执行了return,导致异常被丢失。
可以看到在finally中使用return会导致很多问题。实际应用中,不推荐在finally中使用return返回。

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值