In Python, numerous powerful built-in modules offer convenience to developers. Here are some of the most frequently used built-in modules:
- os module: This module provides functionality for interacting with the operating system. For example, you can use
os.listdir()to list all files and directories within a folder, oros.mkdir()to create a new directory. This is particularly useful for file management and automation scripting.
Example:
pythonimport os # Get the current working directory current_directory = os.getcwd() print("Current directory:", current_directory) # List directory contents directory_contents = os.listdir(current_directory) print("Directory contents:", directory_contents)
- sys module: This module provides access to the Python runtime environment. For example, you can use
sys.argvto handle command-line arguments, orsys.exit()to terminate the script.
Example:
pythonimport sys # Print command-line arguments print("Command-line arguments:", sys.argv) # Exit the program sys.exit()
- datetime module: This module provides functionality for handling dates and times. For example, you can use
datetime.datetime.now()to retrieve the current date and time.
Example:
pythonfrom datetime import datetime # Get current time current_time = datetime.now() print("Current time:", current_time)
- math module: This module offers various mathematical functions and constants. For example, you can use
math.sqrt()to calculate the square root, ormath.pito access the value of pi.
Example:
pythonimport math # Calculate square root print("Square root of 16 is:", math.sqrt(16)) # Value of Pi print("Value of Pi:", math.pi)
- json module: This module is used for handling JSON data. You can use
json.loads()to decode a JSON string into a Python object, orjson.dumps()to encode a Python object into a JSON string.
Example:
pythonimport json # Convert Python dictionary to JSON string data = {"name": "John", "age": 30} json_str = json.dumps(data) print("JSON string:", json_str) # Parse JSON string back to Python dictionary parsed_data = json.loads(json_str) print("Parsed data:", parsed_data)
These modules provide fundamental support for Python programming, making file handling, system operations, time management, mathematical calculations, and data serialization more efficient and straightforward.
2024年8月9日 09:58 回复