前言
上一讲分享了函数,如果重新打开一个文件,上一个文件中的函数方法依然可以调用,这样工作效率会大大提升。这就涉及到本讲的模块与包了。本讲将列举一些常用的模块及其常用方法并采用脑图形式总结。当然这些不要死记硬背,日常编程中常用 dir() 与 help() 内置函数即可。
>>> import os
>>> dir(os)
['DirEntry', 'F_OK', 'MutableMapping', 'O_APPEND', 'O_BINARY', 'O_CREAT', 'O_EXCL', 'O_NOINHERIT', 'O_RANDOM',
'O_RDONLY', 'O_RDWR', 'O_SEQUENTIAL', 'O_SHORT_LIVED', 'O_TEMPORARY', 'O_TEXT', 'O_TRUNC', 'O_WRONLY',
'P_DETACH', 'P_NOWAIT', 'P_NOWAITO', 'P_OVERLAY', 'P_WAIT', 'PathLike', 'R_OK', 'SEEK_CUR', 'SEEK_END',
'SEEK_SET', 'TMP_MAX', 'W_OK', 'X_OK', '_Environ', '__all__', '__builtins__', '__cached__', '__doc__',
'__file__', '__loader__', '__name__', '__package__', '__spec__', '_execvpe', '_exists', '_exit', '_fspath',
'_get_exports_list', '_putenv', '_unsetenv', '_wrap_close', 'abc', 'abort', 'access', 'altsep', 'chdir', 'chmod',
'close', 'closerange', 'cpu_count', 'curdir', 'defpath', 'device_encoding', 'devnull', 'dup', 'dup2', 'environ',
'error', 'execl', 'execle', 'execlp', 'execlpe', 'execv', 'execve', 'execvp', 'execvpe', 'extsep', 'fdopen',
'fsdecode', 'fsencode', 'fspath', 'fstat', 'fsync', 'ftruncate', 'get_exec_path', 'get_handle_inheritable',
'get_inheritable', 'get_terminal_size', 'getcwd', 'getcwdb', 'getenv', 'getlogin', 'getpid', 'getppid', 'isatty',
'kill', 'linesep', 'link', 'listdir', 'lseek', 'lstat', 'makedirs', 'mkdir', 'name', 'open', 'pardir', 'path',
'pathsep', 'pipe', 'popen', 'putenv', 'read', 'readlink', 'remove', 'removedirs', 'rename', 'renames', 'replace',
'rmdir', 'scandir', 'sep', 'set_handle_inheritable', 'set_inheritable', 'spawnl', 'spawnle', 'spawnv', 'spawnve',
'st', 'startfile', 'stat', 'stat_result', 'statvfs_result', 'strerror', 'supports_bytes_environ',
'supports_dir_fd', 'supports_effective_ids', 'supports_fd', 'supports_follow_symlinks', 'symlink', 'sys',
'system', 'terminal_size', 'times', 'times_result', 'truncate', 'umask', 'uname_result', 'unlink', 'urandom',
'utime', 'waitpid', 'walk', 'write']
>>> help(os.getcwd)
Help on built-in function getcwd in module nt:
getcwd()
Return a unicode string representing the current working directory.
1 os
>>> import os
>>> dir(os)
['DirEntry', 'F_OK', 'MutableMapping', 'O_APPEND', 'O_BINARY', 'O_CREAT', 'O_EXCL', 'O_NOINHERIT', 'O_RANDOM',
'O_RDONLY', 'O_RDWR', 'O_SEQUENTIAL', 'O_SHORT_LIVED', 'O_TEMPORARY', 'O_TEXT', 'O_TRUNC', 'O_WRONLY',
'P_DETACH', 'P_NOWAIT', 'P_NOWAITO', 'P_OVERLAY', 'P_WAIT', 'PathLike', 'R_OK', 'SEEK_CUR', 'SEEK_END',
'SEEK_SET', 'TMP_MAX', 'W_OK', 'X_OK', '_Environ', '__all__', '__builtins__', '__cached__', '__doc__',
'__file__', '__loader__', '__name__', '__package__', '__spec__', '_execvpe', '_exists', '_exit', '_fspath',
'_get_exports_list', '_putenv', '_unsetenv', '_wrap_close', 'abc', 'abort', 'access', 'altsep', 'chdir', 'chmod',
'close', 'closerange', 'cpu_count', 'curdir', 'defpath', 'device_encoding', 'devnull', 'dup', 'dup2', 'environ',
'error', 'execl', 'execle', 'execlp', 'execlpe', 'execv', 'execve', 'execvp', 'execvpe', 'extsep', 'fdopen',
'fsdecode', 'fsencode', 'fspath', 'fstat', 'fsync', 'ftruncate', 'get_exec_path', 'get_handle_inheritable',
'get_inheritable', 'get_terminal_size', 'getcwd', 'getcwdb', 'getenv', 'getlogin', 'getpid', 'getppid', 'isatty',
'kill', 'linesep', 'link', 'listdir', 'lseek', 'lstat', 'makedirs', 'mkdir', 'name', 'open', 'pardir', 'path',
'pathsep', 'pipe', 'popen', 'putenv', 'read', 'readlink', 'remove', 'removedirs', 'rename', 'renames', 'replace',
'rmdir', 'scandir', 'sep', 'set_handle_inheritable', 'set_inheritable', 'spawnl', 'spawnle', 'spawnv', 'spawnve',
'st', 'startfile', 'stat', 'stat_result', 'statvfs_result', 'strerror', 'supports_bytes_environ',
'supports_dir_fd', 'supports_effective_ids', 'supports_fd', 'supports_follow_symlinks', 'symlink', 'sys',
'system', 'terminal_size', 'times', 'times_result', 'truncate', 'umask', 'uname_result', 'unlink', 'urandom',
'utime', 'waitpid', 'walk', 'write']
方法 | 描述 | 实例 |
---|---|---|
os.getcwd() | 返回当前工作目录 | >>> os.getcwd() ‘C:\Users\15151’ |
os.chdir(path) | 改变当前工作目录 | >>> os.getcwd() ‘C:\Users\15151’ >>> os.chdir(‘G:/lesson’) >>> os.getcwd() ‘G:\lesson’ |
os.rename(src, dst) | 重命名 | >>> os.listdir(os.getcwd()) [‘test.txt’, ‘test3.txt’] >>> os.rename(‘test.txt’, ‘test2.txt’) >>> os.listdir(os.getcwd()) [‘test2.txt’, ‘test3.txt’] |
os.remove(path) | 移除 path | >>> os.listdir(os.getcwd()) [‘test2.txt’, ‘test3.txt’] >>> os.remove(‘test2.txt’) >>> os.listdir(os.getcwd()) [‘test3.txt’] |
os.path.join(path1, path2) | 链接 path1 与 path2 | >>> os.path.join(‘C:/Users/15151’,‘test3.txt’) ‘C:/Users/15151/test3.txt’ |
2 glob
>>> import glob
>>> dir(glob)
['__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__',
'__spec__', '_glob0', '_glob1', '_glob2', '_iglob', '_ishidden', '_isrecursive', '_iterdir', '_rlistdir',
'escape', 'fnmatch', 'glob', 'glob0', 'glob1', 'has_magic', 'iglob', 'magic_check', 'magic_check_bytes', 'os',
're']
方法 | 描述 | 实例 |
---|---|---|
glob.glob(str) | 返回符合 str 通配符的所有对象 | >>> glob.glob(’*.txt’) [‘test3.txt’] |
3 math
>>> import math
>>> dir(math)
['__doc__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin', 'asinh', 'atan',
'atan2', 'atanh', 'ceil', 'copysign', 'cos', 'cosh', 'degrees', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs',
'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'gcd', 'hypot', 'inf', 'isclose', 'isfinite', 'isinf',
'isnan', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'log2', 'modf', 'nan', 'pi', 'pow', 'radians', 'remainder',
'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'tau', 'trunc']
4 random
>>> import random
>>> dir(random)
['BPF', 'LOG4', 'NV_MAGICCONST', 'RECIP_BPF', 'Random', 'SG_MAGICCONST', 'SystemRandom', 'TWOPI',
'_BuiltinMethodType', '_MethodType', '_Sequence', '_Set', '__all__', '__builtins__', '__cached__', '__doc__',
'__file__', '__loader__', '__name__', '__package__', '__spec__', '_acos', '_bisect', '_ceil', '_cos', '_e',
'_exp', '_inst', '_itertools', '_log', '_os', '_pi', '_random', '_sha512', '_sin', '_sqrt', '_test',
'_test_generator', '_urandom', '_warn', 'betavariate', 'choice', 'choices', 'expovariate', 'gammavariate',
'gauss', 'getrandbits', 'getstate', 'lognormvariate', 'normalvariate', 'paretovariate', 'randint', 'random',
'randrange', 'sample', 'seed', 'setstate', 'shuffle', 'triangular', 'uniform', 'vonmisesvariate',
'weibullvariate']
方法 | 描述 | 实例 |
---|---|---|
random.random() | 返回 [0, 1) 一个随机数 | >>> random.random() 0.307504221005792 |
random.randint(a,b) | 返回 [a, b] 一个整数 | >>> random.randint(1,9) 1 |
random.choice(seq) | 返回 seq 的一个元素 | >>> random.choice(‘hello’) ‘e’ |
random.shuffle(list) | 乱序 | >>> lst = [1,2,3] >>> random.shuffle(lst) >>> print(lst) [3, 2, 1] |
5 time
>>> import time
>>> dir(time)
['_STRUCT_TM_ITEMS', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'altzone', 'asctime',
'clock', 'ctime', 'daylight', 'get_clock_info', 'gmtime', 'localtime', 'mktime', 'monotonic', 'monotonic_ns',
'perf_counter', 'perf_counter_ns', 'process_time', 'process_time_ns', 'sleep', 'strftime', 'strptime',
'struct_time', 'thread_time', 'thread_time_ns', 'time', 'time_ns', 'timezone', 'tzname']
方法 | 描述 | 实例 |
---|---|---|
time.time() | 返回当前时间 | >>> time.time() 1585808425.0772738 |
time.localtime() | 返回当前时区时间 | >>> time.localtime() time.struct_time(tm_year=2020, tm_mon=4, tm_mday=2, tm_hour=14, tm_min=21, tm_sec=20, tm_wday=3, tm_yday=93, tm_isdst=0) |
time.sleep(sec) | 程序睡眠 sec 秒 | >>> time.sleep(1) |
time.strftime() | 转换时间输出形式 | >>> print(time.strftime(’%Y-%m-%d %H:%M:%S’,time.localtime())) 2020-04-02 14:25:39 |
6 file
>>> f = open('test3.txt','w')
>>> print('文件名:',f.name)
文件名: test3.txt
>>> f.write('hello')
5
>>> f.close()
>>> f = open('test3.txt','r')
>>> f.readline()
'hello'
>>> f.close()