Python3 菜鸟教程 笔记8 -- OS、错误和异常

╰+攻爆jí腚メ 2023-06-10 05:30 26阅读 0赞

$ OS
@ OS 文件/目录方法




























































OS 文件/目录方法 Linux 命令类比
os.getcwd()  返回当前工作目录 pwd
os.chdir(path)  改变当前工作目录 cd
os.listdir(path)   返回path指定的文件夹包含的文件或文件夹的名字的列表 ls
os.chmod(path, mode)  更改权限 chmod
os.chown(path, uid, gid)  更改文件所有者 chown
os.rename(src, dst)  重命名文件或目录,从 src 到 dst
os.renames(old, new)  递归地对目录进行更名,也可以对文件进行更名。
参数
old — 要重命名的目录
new —文件或目录的新名字。甚至可以是包含在目录中的文件,或者完整的目录树
mv
os.mkdir(path[, mode])  以数字mode的mode创建一个名为path的文件夹.默认的 mode 是 0777 (八进制)。
os.makedirs(path[, mode])  递归文件夹创建函数。像mkdir(), 但创建的所有intermediate-level文件夹需要包含子文件夹。
 
mkdir
os.remove(path)  删除路径为path的文件。如果path 是一个文件夹,将抛出OSError; 查看下面的rmdir()删除一个 directory。
os.removedirs(path)  递归删除目录。
os.rmdir(path)  删除path指定的空目录,如果目录非空,则抛出一个OSError异常。
如果需要删除非空目录, 你可以使用 shutil模块中的 rmtree函数。
rm
os.readlink(path)  返回软链接所指向的文件  
os.open(file, flags[, mode])  打开一个文件,并且设置需要的打开选项,mode参数是可选的  
os.close(fd)  关闭文件描述符 fd  
os.read(fd, n)  从文件描述符 fd 中读取最多 n 个字节,返回包含读取字节的字符串,文件描述符 fd对应文件已达到结尾, 返回一个空字符串。  
os.write(fd, str)  写入字符串到文件描述符 fd中. 返回实际写入的字符串长度  

@ os.path模块 -> 获取文件的属性信息
传送门 -> https://www.runoob.com/python3/python3-os-path.html

os.path.abspath(path) 返回绝对路径
os.path.basename(path) 返回文件名
os.path.dirname(path) 返回文件路径
os.path.split(path) 把路径分割成 dirname 和 basename,返回一个元组
os.path.exists(path) 路径存在则返回True,路径损坏返回False
os.path.getmtime(path) 返回最近文件修改时间
os.path.getctime(path) 返回文件 path 创建时间
os.path.getsize(path) 返回文件大小,如果文件不存在就返回错误
os.path.isabs(path) 判断是否为绝对路径
os.path.isfile(path) 判断路径是否为文件
os.path.isdir(path) 判断路径是否为目录
os.path.islink(path) 判断路径是否为链接
os.path.ismount(path) 判断路径是否为挂载点
os.path.samefile(path1, path2) 判断目录或文件是否相同
os.path.sameopenfile(fp1, fp2) 判断fp1和fp2是否指向同一文件

[例]注:Windows环境

os.path.basename(‘C:\\eagle\\Friday.txt’)
‘Friday.txt’

os.path.dirname(‘C:\\eagle\\Friday.txt’)
‘C:\\eagle’
os.path.splitext(path) 分割路径,返回路径名和文件扩展名的元组

os.path.split(‘C:\\eagle\\Friday.txt’)
(‘C:\\eagle’, ‘Friday.txt’)

os.path.splitext(‘C:\\eagle\\Friday.txt’)
(‘C:\\eagle\\Friday’, ‘.txt’)

os.path.exists(‘D:\\‘)
False
os.path.join(‘opt’,’sw’,’readme.txt’)
‘opt\\sw\\readme.txt’

$ 错误和异常

@ 语法错误(解析错)SyntaxError

@ 异常处理
[例]让用户输入一个合法的整数,但是允许用户中断这个程序,用户中断的信息会引发一个 KeyboardInterrupt 异常。

while True:
try:
x = int(input(“Please enter a number: “))
break
except ValueError:
print(“Oops! That was no valid number. Try again “)
except KeyboardInterrupt:
print(“You pressed ‘Ctrl+C’…Goodbye~”)
break #这里如果不写break或raise就无限循环了

try语句工作方式;
执行try子句(在关键字try和关键字except之间的语句)
如果没有异常发生,忽略except子句,try子句执行后结束。
如果在执行try子句的过程中发生了异常,那么try子句余下的部分将被忽略。如果异常的类型和 except 之后的名称相符,那么对应的except子句将被执行。最后执行 try 语句之后的代码。
如果一个异常没有与任何的except匹配,那么这个异常将会传递给上层的try中。

说明:
1.一个 try 语句可能包含多个except子句,分别来处理不同的特定的异常。最多只有一个分支会被执行。
2.一个except子句可以同时处理多个异常,这些异常将被放在一个括号里成为一个元组,例如:
except (RuntimeError, TypeError, NameError):
pass
3.最后一个except子句可以忽略异常的名称,它将被当作通配符使用。可以使用这种方法打印一个错误信息,然后再次把异常抛出。
try:

except as err:

except :

except:
print(“Unexpected error:”)
raise

4.try except 语句还有一个可选的else子句,必须放在所有的except子句之后。
这个子句将在try子句没有发生任何异常的时候执行。例如:

for arg in sys.argv[1:]:
try:
f = open(arg, ‘r’)
except IOError:
print(‘cannot open’, arg)
else:
print(arg, ‘has’, len(f.readlines()), ‘lines’)
f.close()

@ 抛出异常 使用raise语句,eg:raise NameError(‘HiThere’)

@ 定义清理行为
try语句还有另外一个可选的finally子句,它定义了无论在任何情况下都会执行的清理行为。
[例]

try:
raise KeyboardInterrupt
finally:
print(‘Goodbye, world!’)

Goodbye, world!
Traceback (most recent call last):
File ““, line 2, in
raise KeyboardInterrupt
KeyboardInterrupt

>

如果一个异常在 try 子句里被抛出,而又没有任何的 except 把它截住,那么这个异常会在 finally 子句执行后被抛出。
[例]

def divide(x, y):
try:
result = x / y
except ZeroDivisionError:
print(“division by zero!”)
else:
print(“result is”, result)
finally:
print(“executing finally clause”)

divide(2, 1)
result is 2.0
executing finally clause
divide(2, 0)
division by zero!
executing finally clause
divide(“2”, “1”)
executing finally clause
Traceback (most recent call last):
File ““, line 1, in ?
File ““, line 3, in divide
TypeError: unsupported operand type(s) for /: ‘str’ and ‘str’

@ 断言 -> 用于判断一个表达式,在表达式条件为 false 的时候触发异常
assert expression
等价于:
if not expression:
raise AssertionError

assert 后面也可以紧跟参数: assert expression [, arguments]
等价于:
if not expression:
raise AssertionError(arguments)

发表评论

表情:
评论列表 (有 0 条评论,26人围观)

还没有评论,来说两句吧...

相关阅读