【python】标准库(第三讲)

🍁作者简介:🏅云计算领域优质创作者🏅新星计划第三季python赛道TOP1🏅 阿里云ACE认证高级工程师🏅

✒️个人主页:小鹏linux

💊个人社区:小鹏linux(个人社区)欢迎您的加入!

【python】标准库(第三讲)【python】标准库(第三讲)

目录

1. OS

1.1 操作文件:重命名、删除文件

1.2 操作目录

1.2.1 os.listdir:显示目录中的文件

1.2.2 os.getcwd, os.chdir:当前工作目录,改变当前工作目录 

1.2.3 os.pardir 的功能是获得父级目录,相当于 ..

1.2.4 os.makedirs, os.removedirs:创建和删除目录

👑👑👑结束语👑👑👑

1. OS

os 模块提供了访问操作系统服务的功能,它所包含的内容比较多。

>>> import os
>>> dir(os)
['EX_CANTCREAT', 'EX_CONFIG', 'EX_DATAERR', 'EX_IOERR', 'EX_NOHOST', 'EX_NOINPUT', 'EX_NOPERM', 'EX_NOUSER','EX_OK', 'EX_OSERR', 'EX_OSFILE', 'EX_PROTOCOL', 'EX_SOFTWARE', 'EX_TEMPFAIL', 'EX_UNAVAILABLE', 'EX_USAGE', 'F_OK', 'NGROUPS_MAX', 'O_APPEND', 'O_ASYNC', 'O_CREAT', 'O_DIRECT', 'O_DIRECTORY', 'O_DSYNC', 'O_EXCL', 'O_LARGEFILE', 'O_NDELAY', 'O_NOATIME', 'O_NOCTTY', 'O_NOFOLLOW', 'O_NONBLOCK', 'O_RDONLY', 'O_RDWR', 'O_RSYNC', 'O_SYNC', 'O_TRUNC', 'O_WRONLY', 'P_NOWAIT', 'P_NOWAITO', 'P_WAIT', 'R_OK', 'SEEK_CUR', 'SEEK_END', 'SEEK_SET', 'ST_APPEND', 'ST_MANDLOCK', 'ST_NOATIME', 'ST_NODEV', 'ST_NODIRATIME', 'ST_NOEXEC', 'ST_NOSUID', 'ST_RDONLY', 'ST_RELATIME', 'ST_SYNCHRONOUS', 'ST_WRITE', 'TMP_MAX', 'UserDict', 'WCONTINUED', 'WCOREDUMP', 'WEXITSTATUS', 'WIFCONTINUED', 'WIFEXITED', 'WIFSIGNALED', 'WIFSTOPPED', 'WNOHANG', 'WSTOPSIG', 'WTERMSIG', 'WUNTRACED', 'W_OK', 'X_OK', '_Environ', '__all__', '__builtins__', '__doc__', '__file__', '__name__', '__package__', '_copy_reg', '_execvpe', '_exists', '_exit', '_get_exports_list', '_make_stat_result', '_make_statvfs_result', '_pickle_stat_result', '_pickle_statvfs_result', '_spawnvef', 'abort', 'access', 'altsep', 'chdir', 'chmod', 'chown', 'chroot', 'close', 'closerange', 'confstr', 'confstr_names', 'ctermid', 'curdir', 'defpath', 'devnull', 'dup', 'dup2', 'environ', 'errno', 'error', 'execl', 'execle', 'execlp', 'execlpe', 'execv', 'execve', 'execvp', 'execvpe', 'extsep', 'fchdir', 'fchmod', 'fchown', 'fdatasync', 'fdopen', 'fork', 'forkpty', 'fpathconf', 'fstat', 'fstatvfs', 'fsync', 'ftruncate', 'getcwd', 'getcwdu', 'getegid', 'getenv', 'geteuid', 'getgid', 'getgroups', 'getloadavg', 'getlogin', 'getpgid', 'getpgrp', 'getpid', 'getppid', 'getresgid', 'getresuid', 'getsid', 'getuid', 'initgroups', 'isatty', 'kill', 'killpg', 'lchown', 'linesep', 'link', 'listdir', 'lseek', 'lstat', 'major', 'makedev', 'makedirs', 'minor', 'mkdir', 'mkfifo', 'mknod', 'name', 'nice', 'open', 'openpty', 'pardir', 'path', 'pathconf', 'pathconf_names', 'pathsep', 'pipe', 'popen', 'popen2', 'popen3', 'popen4', 'putenv', 'read', 'readlink', 'remove', 'removedirs', 'rename', 'renames', 'rmdir', 'sep', 'setegid', 'seteuid', 'setgid', 'setgroups', 'setpgid', 'setpgrp', 'setregid', 'setresgid', 'setresuid', 'setreuid', 'setsid', 'setuid', 'spawnl', 'spawnle', 'spawnlp', 'spawnlpe', 'spawnv', 'spawnve', 'spawnvp', 'spawnvpe', 'stat', 'stat_float_times', 'stat_result', 'statvfs', 'statvfs_result', 'strerror', 'symlink', 'sys', 'sysconf', 'sysconf_names', 'system', 'tcgetpgrp', 'tcsetpgrp', 'tempnam', 'times', 'tmpfile', 'tmpnam', 'ttyname', 'umask', 'uname', 'unlink', 'unsetenv', 'urandom', 'utime', 'wait', 'wait3', 'wait4', 'waitpid', 'walk', 'write']

【python】标准库(第三讲)

这么多内容不能都介绍,况且不少方法在实践中用的不多,比如 os.popen() 在实践中用到了,但是 os 模块还

有 popen2、popen3、popen4,这三个我在实践中都没有用过,或者有别人用了,也请补充。不过,我下面介绍的都是自认为用的比较多的,至少是我用的比较多或者用过的。我这里没有介绍,大家也完全可以自己用我们常用的 help() 来自学明白其应用方法,当然,还有最好的工具——google(内事不决问 google,外事不明问谷歌,须搭天梯)。

1.1 操作文件:重命名、删除文件

在对文件操作的时候, open() 这个内建函数可以建立、打开文件。但是,如果对文件进行改名、删除操作,就要是用 os 模块的方法了。

首先建立一个文件,文件名为 22201.py,文件内容是:

#!/usr/bin/env python
# coding=utf-8
print "This is a tmp file."

【python】标准库(第三讲)

然后将这个文件名称修改为其它的名称。

>>> import os
>>> os.rename("22201.py", "newtemp.py")

【python】标准库(第三讲)

注意,我是先进入到了文件 22201.py 的目录,然后进入到 Python 交互模式,所以,可以直接写文件名,如果不是这样,需要将文件名的路径写上。 os.rename("22201.py", "newtemp.py") 中,第一个文件是原文件名

称,第二个是打算修改成为的文件名。

$ ls new*
newtemp.py

查看,能够看到这个文件。并且文件内容可以用 cat newtemp.py 看看(这是在 linux 系统,如果是 window

s 系统,可以用其相应的编辑器打开文件看内容)。

Help on built-in function rename in module posix:
rename(...)
    rename(old, new)
    Rename a file or directory

【python】标准库(第三讲)

除了修改文件名称,还可以修改目录名称。请注意阅读帮助信息。

另外一个 os.remove(),首先看帮助信息,然后再实验。

Help on built-in function remove in module posix:
remove(...)
    remove(path)
    Remove a file (same as unlink(path)).

【python】标准库(第三讲)

比较简单。那就测试一下。为了测试,先建立一些文件吧。

$ pwd
/home/qw/Documents/VBS/StarterLearningPython/2code/rd

【python】标准库(第三讲)

这是我建立的临时目录,里面有几个文件:

$ ls
a.py b.py c.py

【python】标准库(第三讲)

下面删除 a.py 文件

>>> import os
>>> os.remove("/home/qw/Documents/VBS/StarterLearningPython/2code/rd/a.py")

【python】标准库(第三讲)

看看删了吗?

$ ls
b.py c.py

【python】标准库(第三讲)

果然管用呀。再来一个狠的:

>>> os.remove("/home/qw/Documents/VBS/StarterLearningPython/2code/rd")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
OSError: [Errno 21] Is a directory: '/home/qw/Documents/VBS/StarterLearningPython/2code/rd'

【python】标准库(第三讲)

报错了。我打算将这个目录下的所剩文件删光光。这么做不行。注意帮助中一句话 Remove a file ,os.remov

e() 就是用来删除文件的。并且从报错中也可以看到,告诉我们错误的原因在于那个参数是一个目录。

要删除目录,还得继续向下学习。

1.2 操作目录

1.2.1 os.listdir:显示目录中的文件

Help on built-in function listdir in module posix:
listdir(...)
    listdir(path) -> list_of_strings
Return a list containing the names of the entries in the directory.
    path: path of directory to list
The list is in arbitrary order. It does not include the special
entries '.' and '..' even if they are present in the directory.

【python】标准库(第三讲)

看完帮助信息,大家一定觉得这是一个非常简单的方法,不过,特别注意它返回的值是列表,还有就是如果文件夹中有那样的特殊格式命名的文件,不显示。在 linux 中,用 ls 命令也看不到这些隐藏的东东。

>>> os.listdir("/home/qw/Documents/VBS/StarterLearningPython/2code/rd")
['b.py', 'c.py']
>>> files = os.listdir("/home/qw/Documents/VBS/StarterLearningPython/2code/rd")
>>> for f in files:
... print f
...
b.py
c.py

【python】标准库(第三讲)

1.2.2 os.getcwd, os.chdir:当前工作目录,改变当前工作目录

这两个函数怎么用?惟有通过 help() 看文档啦。请大家自行看看。我就不贴出来了,仅演示一个例子:

>>> cwd = os.getcwd() #当前目录
>>> print cwd
/home/qw/Documents/VBS/StarterLearningPython/2code/rd
>>> os.chdir(os.pardir) #进入到上一级
>>> os.getcwd() #当前
'/home/qw/Documents/VBS/StarterLearningPython/2code'
>>> os.chdir("rd") #进入下级
>>> os.getcwd()
'/home/qw/Documents/VBS/StarterLearningPython/2code/rd'

【python】标准库(第三讲)

1.2.3 os.pardir 的功能是获得父级目录,相当于 ..

>>> os.pardir
'..'

【python】标准库(第三讲)

1.2.4 os.makedirs, os.removedirs:创建和删除目录

废话少说,路子还是前面那样,就省略看帮助了,大家可以自己看。直接上例子:

>>> dir = os.getcwd()
>>> dir
'/home/qw/Documents/VBS/StarterLearningPython/2code/rd'
>>> os.removedirs(dir)
Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
    File "/usr/lib/python2.7/os.py", line 170, in removedirs
        rmdir(name)
OSError: [Errno 39] Directory not empty: '/home/qw/Documents/VBS/StarterLearningPython/2code/rd'

【python】标准库(第三讲)

什么时候都不能得意忘形,一定要谦卑。那就是从看文档开始一点一点地理解。不能像上面那样,自以为是、贸然行事。看报错信息,要删除某个目录,那个目录必须是空的。

>>> os.getcwd()
'/home/qw/Documents/VBS/StarterLearningPython/2code'

【python】标准库(第三讲)

这是当前目录,在这个目录下再建一个新的子目录:

>>> os.makedirs("newrd")
>>> os.chdir("newrd")
>>> os.getcwd()
'/home/qw/Documents/VBS/StarterLearningPython/2code/newrd'

【python】标准库(第三讲)

建立了一个。下面把这个删除了。这个是空的。

>>> os.listdir(os.getcwd())
[]
>>> newdir = os.getcwd()
>>> os.removedirs(newdir)

【python】标准库(第三讲)

按照我的理解,这里应该报错。因为我是在当前工作目录删除当前工作目录。如果这样能够执行,总觉得有点别扭。但事实上,就行得通了。就算是 python 的规定吧。不过,让我来确定这个功能的话,还是习惯不能在本地删除本地。

按照上面的操作,在看当前工作目录:

>>> os.getcwd()
Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
OSError: [Errno 2] No such file or directory

【python】标准库(第三讲)

目录被删了,当然没有啦。只能回到父级

>>> os.chdir(os.pardir)
>>> os.getcwd()
'/home/qw/Documents/VBS/StarterLearningPython/2code

【python】标准库(第三讲)

有点不可思议。本来没有当前工作目录,怎么会有“父级”的呢?但 Python 就是这样。

补充一点,前面说的如果目录不空,就不能用 os.removedirs() 删除。但是,可以用模块 shutil 的 retree 方 法。

>>> os.getcwd()
'/home/qw/Documents/VBS/StarterLearningPython/2code'
>>> os.chdir("rd")
>>> now = os.getcwd()
>>> now
'/home/qw/Documents/VBS/StarterLearningPython/2code/rd'
>>> os.listdir(now)
['b.py', 'c.py']
>>> import shutil
>>> shutil.rmtree(now)
>>> os.getcwd()
Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
OSError: [Errno 2] No such file or directory

【python】标准库(第三讲)

请大家注意的是,对于 os.makedirs() 还有这样的特点:

>>> os.getcwd()
'/home/qw/Documents/VBS/StarterLearningPython/2code'
>>> d0 = os.getcwd()
>>> d1 = d0+"/ndir1/ndir2/ndir3" #这是想建立的目录,但是中间的 ndir1,ndir2 也都不存在。
>>> d1
'/home/qw/Documents/VBS/StarterLearningPython/2code/ndir1/ndir2/ndir3'
>>> os.makedirs(d1)
>>> os.chdir(d1)
>>> os.getcwd()
'/home/qw/Documents/VBS/StarterLearningPython/2code/ndir1/ndir2/ndir3'

【python】标准库(第三讲)

中间不存在的目录也被建立起来,直到做右边的目录为止。与 os.makedirs() 类似的还有 os.mkdir(),不过, os.mkdir() 没有上面这个功能,它只能一层一层地建目录。

os.removedirs() os.rmdir() 也类似,区别也类似上面。

👑👑👑结束语👑👑👑

【python】标准库(第三讲)【python】标准库(第三讲)