Python 教程 8: 标准库 (Standard Library)
Brief Tour of the Standard Library
Operating System Interface
The os module provides dozens of functions for interacting with the operating system:
import os
os.getcwd() # Return the current working directory
'C:\\Python312'
os.chdir('/server/accesslogs') # Change current working directory
os.system('mkdir today') # Run the command mkdir in the system shell
0
Be sure to use the import os style instead of from os import *. This will keep os.open() from shadowing the built-in open() function which operates much differently.
File Wildcards
The glob module provides a function for making file lists from directory wildcard searches:
import glob
glob.glob('*.py')
['primes.py', 'random.py', 'quote.py']
Command Line Arguments
Common utility scripts often need to process command line arguments. These arguments are stored in the sys module’s argv attribute as a list. For instance the following output results from running python demo.py one two three at the command line:
import sys
print(sys.argv)
['demo.py', 'one', 'two', 'three']