python基礎4:os模塊、shutil模塊 和 python shell快捷鍵

一、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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章