Python:作業系統模組簡介
OS module
- in order to import OS module we use
import os
- To print all the available options in a method/function
import os print(dir(os))
- to print Current working directory we use
import os print(os.getcwd())
- to print directory location we use
import os path='/home/user/' # printing path before changing directory print(os.getcwd()) # function used for changing directory os.chdir(path) # printing path after changing directory print(os.getcwd()) # to list directories print(os.listdir())
- To make a single directory without any intermediate directories
import os # this wont create intermediate directories os.makedir('single_dir') print(os.listdir())
- To make a multiple directories with intermediate directories
import os # this will create intermediate directories os.makedirs('parent_dir/child_dir') print(os.listdir())
- To remove a single directory
import os # this wont remove intermediate directories os.rmdir('path') print(os.listdir())
- To remove a multiple directory
import os # this will remove intermediate directories os.removedirs('path1/path2') print(os.listdir())
- To rename a directory
import os # this will remove intermediate directories os.rename('old-name','new-name') print(os.listdir())
- To print information about OS, we use os.stat() function
import os import datetime from datetime # this will remove intermediate directories print(os.stat('file-name')) # Example : to print when file was created file_created = os.stat('file-name').st_mtime print(datetime.fromtimestamp(file_created))
- To list information about directories & Subdirectories
import os path = os.chdir('path') # Example : to print all the files under that above path for dirpath, dirname, filename in os.walk(): print('Current Path:',dirpath) print('Directories:',dirname) print('filename:',filename) print()
- To print Environment variables
import os # to print Environment variable home print(os.environ.get('HOME'))
-
To interact with path we use os.path module
Examples of path module
import os # to check if given path exists or not print(os.path.exists('/home/user1/text.txt')) # to check if given path is a directory or file print(os.path.isdir('/home/user2/demo')) print(os.path.isfilek('/home/user2/demo')) # to split filname name from extenstion we use print(os.path.splitext('/home/demo1/book.txt')) # to print basename of any file we use print(os.path.basename('/home/demo1/book.txt')) # to print the directory name we use print(os.path.dirname('/home/demo1/book.txt')) # to print both, dirname + basename we use print(os.path.split('/home/demo1/book.txt')) # to join paths we use file_path = os.path.join(os.environ.get('HOME'),'test.txt') print(file_path)
以上是Python:作業系統模組簡介的詳細內容。更多資訊請關注PHP中文網其他相關文章!

熱AI工具

Undress AI Tool
免費脫衣圖片

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

記事本++7.3.1
好用且免費的程式碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
強大的PHP整合開發環境

Dreamweaver CS6
視覺化網頁開發工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

多態是Python面向對象編程中的核心概念,指“一種接口,多種實現”,允許統一處理不同類型的對象。 1.多態通過方法重寫實現,子類可重新定義父類方法,如Animal類的speak()方法在Dog和Cat子類中有不同實現。 2.多態的實際用途包括簡化代碼結構、增強可擴展性,例如圖形繪製程序中統一調用draw()方法,或遊戲開發中處理不同角色的共同行為。 3.Python實現多態需滿足:父類定義方法,子類重寫該方法,但不要求繼承同一父類,只要對象實現相同方法即可,這稱為“鴨子類型”。 4.注意事項包括保持方

迭代器是實現__iter__()和__next__()方法的對象,生成器是簡化版的迭代器,通過yield關鍵字自動實現這些方法。 1.迭代器每次調用next()返回一個元素,無更多元素時拋出StopIteration異常。 2.生成器通過函數定義,使用yield按需生成數據,節省內存且支持無限序列。 3.處理已有集合時用迭代器,動態生成大數據或需惰性求值時用生成器,如讀取大文件時逐行加載。注意:列表等可迭代對像不是迭代器,迭代器到盡頭後需重新創建,生成器只能遍歷一次。

類方法是Python中通過@classmethod裝飾器定義的方法,其第一個參數為類本身(cls),用於訪問或修改類狀態。它可通過類或實例調用,影響的是整個類而非特定實例;例如在Person類中,show_count()方法統計創建的對像數量;定義類方法時需使用@classmethod裝飾器並將首參命名為cls,如change_var(new_value)方法可修改類變量;類方法與實例方法(self參數)、靜態方法(無自動參數)不同,適用於工廠方法、替代構造函數及管理類變量等場景;常見用途包括從

參數(parameters)是定義函數時的佔位符,而傳參(arguments)是調用時傳入的具體值。 1.位置參數需按順序傳遞,順序錯誤會導致結果錯誤;2.關鍵字參數通過參數名指定,可改變順序且提高可讀性;3.默認參數值在定義時賦值,避免重複代碼,但應避免使用可變對像作為默認值;4.args和*kwargs可處理不定數量的參數,適用於通用接口或裝飾器,但應謹慎使用以保持可讀性。

處理API認證的關鍵在於理解並正確使用認證方式。 1.APIKey是最簡單的認證方式,通常放在請求頭或URL參數中;2.BasicAuth使用用戶名和密碼進行Base64編碼傳輸,適合內部系統;3.OAuth2需先通過client_id和client_secret獲取Token,再在請求頭中帶上BearerToken;4.為應對Token過期,可封裝Token管理類自動刷新Token;總之,根據文檔選擇合適方式,並安全存儲密鑰信息是關鍵。

Python的magicmethods(或稱dunder方法)是用於定義對象行為的特殊方法,它們以雙下劃線開頭和結尾。 1.它們使對象能夠響應內置操作,如加法、比較、字符串表示等;2.常見用例包括對像初始化與表示(__init__、__repr__、__str__)、算術運算(__add__、__sub__、__mul__)及比較運算(__eq__、__lt__);3.使用時應確保其行為符合預期,例如__repr__應返回可重構對象的表達式,算術方法應返回新實例;4.應避免過度使用或以令人困惑的方

Pythonmanagesmemoryautomaticallyusingreferencecountingandagarbagecollector.Referencecountingtrackshowmanyvariablesrefertoanobject,andwhenthecountreacheszero,thememoryisfreed.However,itcannothandlecircularreferences,wheretwoobjectsrefertoeachotherbuta

Python的垃圾回收機制通過引用計數和周期性垃圾收集來自動管理內存。其核心方法是引用計數,當對象的引用數為零時立即釋放內存;但無法處理循環引用,因此引入了垃圾收集模塊(gc)來檢測並清理循環。垃圾回收通常在程序運行中引用計數減少、分配與釋放差值超過閾值或手動調用gc.collect()時觸發。用戶可通過gc.disable()關閉自動回收、gc.collect()手動執行、gc.set_threshold()調整閾值以實現控制。並非所有對像都參與循環回收,如不包含引用的對象由引用計數處理,內置
