一、OS模块
os模块代码及描述:
作用 | 代码 |
---|---|
os.getcwd() | 得到当前工作目录,即当前Python脚本工作的目录路径 |
os.listdir() | 返回指定目录下的所有文件和目录名 |
os.rename(old, new) | 重命名 |
os.mkdir(“test”) | 创建单个目录 |
os.makedirs(path) | 创建多级目录 ; os.makedirs(r“c:\python\test”) |
os.remove() | 函数用来删除一个文件 |
os.removedirs(r”c:\python”) | 删除多个目录 |
os.path.isfile() | 检验给出的路径是否是一个文件 |
os.path.isdir() | 检验给出的路径是否是一个目录 |
os.path.isabs() | 判断是否是绝对路径 |
os.path.exists() | 检验给出的路径是否存在 |
os.path.split() | 返回一个路径的目录名和文件名。eg:os.path.split(‘/home/swaroop/byte/code/poem.txt’);结果:(‘/home/swaroop/byte/code’, ‘poem.txt’) |
os.path.splitext() | 分离扩展名 |
os.path.dirname() | 获取路径名 |
os.path.basename() | 获取文件名 |
os.system() | 运行shell命令 |
os.getenv() 与os.putenv() | 读取和设置环境变量 |
os.linesep | 给出当前平台使用的行终止符 (Windows使用’\r\n’,Linux使用’\n’而Mac使用’\r’) |
os.name | 指示你正在使用的平台 (对于Windows,它是’nt’,而对于Linux/Unix用户,它是’posix’) |
os.stat(file) | 获取文件属性 |
os.chmod(file) | 修改文件权限与时间戳 |
os.exit() | 终止当前进程 |
os.path.getsize(filename) | 获取文件大小 |
>>> os.getcwd()
'C:\\Python34'
>>> os.listdir()
['DLLs', 'Doc', 'include', 'Lib', 'libs', 'LICENSE.txt', 'NEWS.txt', 'python.exe', 'pythonw.exe', 'README.txt', 'Scripts', 'tcl', 'Tools']
>>> os.path.isdir(os.getcwd())
True
if not os.path.exists(srcPath):
print('srcPath % is not exists' % srcPath)
return None
# 如果目标路径不存在,创建目标文件夹(有可能会创建失败)
if not os.path.exists(destPath):
# 防御性编程 try: except:
try:
os.mkdir(destPath) # 创建目录
except:
print('mkdir %s error' % destPath)
二、OS模块 & shutil模块
代码 | 描述 |
---|---|
os.mkdir(“file”) | 创建目录 |
shutil.copyfile(“oldfile”,”newfile”) | 复制文件, oldfile和newfile都只能是文件 |
shutil.copy(“oldfile”,”newfile”) | 复制文件, oldfile只能是文件夹,newfile可以是文件,也可以是目标目录 |
shutil.copytree(“olddir”,”newdir”) | 复制文件夹, olddir和newdir都只能是目录,且newdir必须不存在 |
os.rename(“oldname”,”newname”) | 重命名文件(目录),文件或目录都是使用这条命令 |
shutil.move(“oldpos”,”newpos”) | 移动文件(目录) |
os.remove(“file”) | 删除文件 |
os.rmdir(“dir”) | 删除目录,只能删除空目录 |
shutil.rmtree(“dir”) | 删除目录, 空目录、有内容的目录都可以删 |
os.chdir(“path”) | 转换目录, 换路径 |
三、python shell快捷键
1、python shell下清屏操作
- Linux shell: clear
- windows cmd: cls
对应的,如果在python交互模式下清屏,就利用 os.system() 来调用对应
的命令即可。
2、IDLE编辑器快捷键(部分)
快捷键 | 作用 |
---|---|
Alt+P | 上一条命令 |
Alt+N | 下一条命令 |
F1 | 打开Python文档 |
Alt+M | 打开代码模块 |
Alt+/ | 自动补全代码(查找编辑器内已经写过的代码来补全) |
Ctrl+Shift+space | 补全提示 |
Ctrl+Z | 后退 |
Ctrl+Shift+Z | 重做 |
Ctrl+] | 加缩进 |
Ctrl+[ | 减缩进 |
Alt+3 | 加注释 |
Alt+4 | 去注释 |
settings中快捷键位置如图:
import os
os.system('cls') # window
os.system('clear') # linux