Python3 2官方文件翻譯 標準庫概覽(一)

2021-06-22 00:22:19 字數 1694 閱讀 6443

os模組提供主要許多與作業系統互動的函式。

>>> import os

>>> os.getcwd() # return the current working directory

』c:\\python31

』>>> os.chdir(』

/server/accesslogs

』) # change current working directory

>>> os.system(』

mkdir today

』) # run the command mkdir in the system shell0

一定要用import os 

方式代替 

from os import *. 

這會使os.open()

方法覆蓋內建的

open()

函式。因為它們操作有很大的不同。

內建方法dir()

和help()

方法對互動的使用像

os這種大模組非常有用。

>>> import os

>>> dir(os)

>>> help(os) 』

s docstrings>

對於日用檔案和目錄管理任務,shutill

模組提供乙個更高階別的並方便使用的介面。

>>> import shutil

>>> shutil.copyfile(』

data.db』, 

』archive.db』)

>>> shutil.move(』

/build/executables』, 

』installdir』)

glob模組提供乙個函式用來從目錄萬用字元搜尋中生產檔案列表。

>>> import glob

>>> glob.glob(』

*.py』)

[』primes.py』, 

』random.py』, 

』quote.py』]

共同的工具指令碼常常需要提供命令列引數。這些引數作為列表儲存在sys

模組中argv

屬性中。例如,接下來輸出通過在命令列執行

python demo.py one two three 

得到的結果。

>>> import sys

>>> print(sys.argv) [』

demo.py』, 

』one』, 

』two』, 

』three』]

getopt模組用

unix

的習慣getopt()

函式來執行

sys.argv. 

在argparse

模組提供了許多更加作用強大和靈活的命令列操作。

sys模組還包括許多屬性如 

stdin

,stdout

和stderr

。後面的屬性通常用來丟擲警告或者錯誤資訊,當

stdout

重定向時候也可以看到錯誤資訊。

終止指令碼的最直接方法就是用sys.exit()

方法。

>>> sys.stderr.write(』

warning, log file not found starting a new one\n』)

warning, log file not found starting a new one

Python3 2官方文件翻譯 模板

string模組包含乙個用途廣泛的類,此類為終端使用者的編輯提供了簡單的語法支援。這讓使用者不修改應用程式的前提下實現他們應用程式的定製。這種格式使用 加有效的 python 識別符號 數字 字母和下劃線 形式的佔位符名稱。通過在佔位符兩側使用大括號便可以不用空格分隔在其後面跟隨更多的字母和數字字元...

Python3 2官方文件翻譯 迭代器

到眼下為止。你可能已注意到很多容器物件都能夠用for 語句進行迴圈 這樣的訪問風格清楚簡潔方便。迭代器的應用是python 遍歷統一。在這樣的場景背後。for語句呼叫容器物件 iter 方法。函式返回乙個迭代器物件。在迭代器物件裡定義了每次僅僅能訪問乙個元素的方法 next 當容器裡面沒有元素的時候...

Python3 2官方文件翻譯 檔案讀寫

open 方法返回乙個檔案物件,在大多數情況下傳遞兩個物件 open filename,mode 例如 f open tmp workfile w 第乙個引數是包含檔名稱的字串,第二個引數是包含描述檔案使用方式的字串。如果檔案唯讀標記為 r 只寫標記為 w 相同名字的已經存在檔案將會被清除 a 表示...