Python學習筆記之讀取檔案、OS模組、異常處理、with as語法示例
阿新 • • 發佈:2020-12-30
轉:https://m.sogou.com/web/id=4c468b90-3f64-418c-acf8-990b5fe2a757/keyword=python%20os%E6%A8%A1%E5%9D%97%E8%AF%BB%E5%8F%96%E8%AE%B0%E4%BA%8B%E6%9C%AC%E5%86%85%E5%AE%B9/sec=4NxQ7Q1PJSfDB2N8MPATLA../tc?clk=5&url=https%3A%2F%2Fwww.jb51.net%2Farticle%2F162468.htm&pid=sogou-clse-2996962656838a97&e=1427&de=1&dp=1&rcer=gXdGqO_Po_Z6XqxOP&is_per=0&pno=1&vrid=30000000&wml=0&linkid=summary&clickTime=1609212904959&mcv=44&pcl=348,1428&sed=0&ml=9&sct=142
檔案讀取 #讀取檔案 f = open("test.txt","r") print(f.read()) #列印檔案內容 #關閉檔案 f.close() 獲取檔案絕對路徑:OS模組 os.environ["xxx"] 獲取系統環境變數 os.getcwd 獲取當前python指令碼工作路徑 os.getpid() 獲取當前程序ID os.getppid() 獲取父程序ID 異常 #讀取檔案 f = None try: f = open("test.txt", "r") print(f.read()) except BaseException: print("檔案沒有找到") finally: if f is not None: f.close() with as語法 #讀取檔案 with open("test.txt","r") as f: print(f.read()) f.close()