# python 常用 ###### tags: `python` # time ``` import time,datetime print(datetime.date.today()) #2019-11-11 print(datetime.datetime.now()) #2019-11-11 16:36:21.141349 ``` # File [reference](https://www.itread01.com/content/1549615343.html) |說明| 指令 | | -------- | -------- | | 得到當前工作目錄,即當前Python指令碼工作的目錄路徑| os.getcwd()| |返回指定目錄下的所有檔案和目錄名|os.listdir()| |函式用來刪除一個檔案|os.remove()| |刪除多個目錄|os.removedirs(r“c:\python”)| |檢驗給出的路徑是否是一個檔案|os.path.isfile()| |檢驗給出的路徑是否是一個目錄|os.path.isdir()| |判斷是否是絕對路徑|os.path.isabs()| |檢驗給出的路徑是否真地存|os.path.exists()| |返回一個路徑的目錄名和檔名|os.path.split()| |例 os.path.split(‘/home/swaroop/byte/code/poem.txt’) 結果:(‘/home/swaroop/byte/code’, ‘poem.txt’)| |分離副檔名|os.path.splitext()| |獲取路徑名|os.path.dirname()| |獲取檔名|os.path.basename()| |執行shell命令|os.system()| |讀取和設定環境變數|os.getenv() 與os.putenv()| ``` with open('C:\Desktop\text.txt','w') as f: f.write('Hello, python!') ``` os.mknod(“test.txt”) 建立空檔案 fp = open(“test.txt”,w) 直接開啟一個檔案,如果檔案不存在則建立檔案 fp.write(str) 寫入txt裡一段字串 fp.close() 寫完記得關掉,不然無法存取txt 目錄操作: 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”) 換路徑 ### os.listdir ``` #!/usr/bin/python # -*- coding: utf-8 -*- from os import listdir from os.path import isfile, isdir, join # 指定要列出所有檔案的目錄 mypath = "/var/log" # 取得所有檔案與子目錄名稱 files = listdir(mypath) # 以迴圈處理 for f in files: # 產生檔案的絕對路徑 fullpath = join(mypath, f) # 判斷 fullpath 是檔案還是目錄 if isfile(fullpath): print("檔案:", f) elif isdir(fullpath): print("目錄:", f) ``` output ``` 目錄: lightdm 目錄: ntpstats 檔案: Xorg.0.log 檔案: messages 檔案: bootstrap.log [略] ``` ### os.walk ``` #!/usr/bin/python # -*- coding: utf-8 -*- from os import walk from os.path import join # 指定要列出所有檔案的目錄 mypath = "/var/log" # 遞迴列出所有檔案的絕對路徑 for root, dirs, files in walk(mypath): for f in files: fullpath = join(root, f) print(fullpath) ``` output ``` /var/log/Xorg.0.log /var/log/messages /var/log/bootstrap.log [略] /var/log/boot.log /var/log/apt/term.log /var/log/apt/history.log /var/log/fsck/checkfs /var/log/fsck/checkroot ``` ### print ```python text = 'world' print('hello {}'.format(text)) # hello world ############################### name = 'Jack' text = 'world' print('hello {name}, hello {text}'.format(name=name, text=text)) # hello Jack, hello world ############################### text = 'world' print(f'Hello, {text}') ############################### x = 10 y = 27 print(f'x + y = {x + y}') # 37 ``` # import 介紹 [Python 的 Import](https://medium.com/pyladies-taiwan/python-%E7%9A%84-import-%E9%99%B7%E9%98%B1-3538e74f57e3) # opencv ### 讀圖 ``` import numpy as np import cv2 # 讀取圖檔 img = cv2.imread('image.jpg') # 查看資料型態 type(img) img.shape #(1080,1920,3) # 以灰階的方式讀取圖檔 img_gray = cv2.imread('image.jpg', cv2.IMREAD_GRAYSCALE) # 顯示圖片 cv2.imshow('My Image', img) # 按下任意鍵則關閉所有視窗 cv2.waitKey(0) cv2.destroyAllWindows() ``` ### 寫檔 ``` # 寫入圖檔 cv2.imwrite('output.jpg', img) # 寫入不同圖檔格式 cv2.imwrite('output.png', img) cv2.imwrite('output.tiff', img) # 設定 JPEG 圖片品質為 90(可用值為 0 ~ 100) cv2.imwrite('output.jpg', img, [cv2.IMWRITE_JPEG_QUALITY, 90]) # 設定 PNG 壓縮層級為 5(可用值為 0 ~ 9) cv2.imwrite('output.png', img, [cv2.IMWRITE_PNG_COMPRESSION, 5]) ``` ### 影片 ``` import cv2 # 選擇第二隻攝影機 cap = cv2.VideoCapture(1) #rtsp #cap = cv2.VideoCapture('rtsp://admin:admin@203.64.95.155:8554') # 取得影像的尺寸大小 width = cap.get(cv2.CAP_PROP_FRAME_WIDTH) height = cap.get(cv2.CAP_PROP_FRAME_HEIGHT) print("Image Size: %d x %d" % (width, height)) # 設定影像的尺寸大小 cap.set(cv2.CAP_PROP_FRAME_WIDTH, 1280) cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 960) while(True): # 從攝影機擷取一張影像 ret, frame = cap.read() if(ret==False): break # 顯示圖片 cv2.imshow('frame', frame) # 若按下 q 鍵則離開迴圈 if cv2.waitKey(1) & 0xFF == ord('q'): break if cv2.waitKey(5) == 27: break # 釋放攝影機 cap.release() # 關閉所有 OpenCV 視窗 cv2.destroyAllWindows() ``` ### 寫影片 ``` #轉檔 MP4 > WMV video_file='123.mp4' cap=cv2.VideoCapture(video_file) #影片存檔 video_fps=int(cap.get(cv2.CAP_PROP_FPS)) #FPS fourcc = cv2.VideoWriter_fourcc(*'WMVV') #格式WMV video_size=(int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)),int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))) video_out=cv2.VideoWriter() video_name='456.wmv' #output檔名 video_out.open(video_name, fourcc, video_fps, video_size, True) while(True): ret, frame = cap.read() # 若讀取至影片結尾,則跳出 if(ret==False): break if cv2.waitKey(1) & 0xFF ==27: break video_out.write(frame) #寫入去識別影片 #cv2.imshow('frame', frame) #原圖 #若按下 esc 鍵則離開迴圈 #釋放攝影機 cap.release() #影片存檔釋放 video_out.release() ``` ### web https://2.python-requests.org//zh_CN/latest/user/quickstart.html ### pygame ```python import time import pygame file=r'C:\Users\chan\Desktop\Adele - All I Ask.mp3' pygame.mixer.init() print("播放音樂1") track = pygame.mixer.music.load(file) #播10秒停止 pygame.mixer.music.play() time.sleep(10) pygame.mixer.music.stop() ``` [如何安裝Anaconda,並且匯入conda虛擬環境](https://medium.com/qiubingcheng/%E5%A6%82%E4%BD%95%E5%AE%89%E8%A3%9Danaconda-%E4%B8%A6%E4%B8%94%E5%8C%AF%E5%85%A5conda%E8%99%9B%E6%93%AC%E7%92%B0%E5%A2%83-ba2e140706a3)