Python内置函数示例

Must Watch!





Guide to Python Built-in Functions

Mathematical Functions abs() – returns the absolute value of a number pow() – raises a number to a specified power round() – rounds a number to a specified number of decimal places max() – returns the largest value in a list or tuple min() – returns the smallest value in a list or tuple print(abs(-10)) # Output: 10 print(pow(2, 3)) # Output: 8 print(round(3.14159, 2)) # Output: 3.14 print(max(2, 5, 8, 1)) # Output: 8 print(min(2, 5, 8, 1)) # Output: 1 divmod() - returns the quotient and remainder when one number is divided by another sum() - returns the sum of all the elements in a list or tuple round() - rounds a number to the nearest integer floor() - returns the largest integer less than or equal to a given number ceil() - returns the smallest integer greater than or equal to a given number print(divmod(10, 3)) # Output: (3, 1) my_list = [1, 2, 3, 4, 5] print(sum(my_list)) # Output: 15 print(round(3.7)) # Output: 4 import math print(math.floor(3.9)) # Output: 3 print(math.ceil(3.1)) # Output: 4 String Functions len() – returns the length of a string capitalize() – capitalizes the first letter of a string replace() – replaces a specified substring with another substring split() – splits a string into a list of substrings based on a specified delimiter join() – joins a list of strings into a single string using a specified delimiter text = "hello world" print(len(text)) # Output: 11 print(text.capitalize()) # Output: Hello world print(text.replace("world", "Python")) # Output: hello Python print(text.split(" ")) # Output: ['hello', 'world'] words = ["hello", "world"] print(" ".join(words)) # Output: hello world lower() – returns a string in all lowercase letters upper() – returns a string in all uppercase letters strip() – removes leading and trailing whitespace from a string startswith() – returns True if a string starts with a specified substring endswith() – returns True if a string ends with a specified substring text = " Hello, World! " print(text.lower()) # Output: " hello, world! " print(text.upper()) # Output: " HELLO, WORLD! " print(text.strip()) # Output: "Hello, World!" print(text.startswith("Hello")) # Output: False print(text.endswith("!")) # Output: True List Functions append() – adds an element to the end of a list remove() – removes the first occurrence of a specified element from a list sort() – sorts the elements of a list reverse() – reverses the order of the elements in a list count() – returns the number of times a specified element appears in a list fruits = ["apple", "banana", "cherry"] fruits.append("orange") print(fruits) # Output: ['apple', 'banana', 'cherry', 'orange'] fruits.remove("banana") print(fruits) # Output: ['apple', 'cherry', 'orange'] fruits.sort() print(fruits) # Output: ['apple', 'cherry', 'orange'] fruits.reverse() print(fruits) # Output: ['orange', 'cherry', 'apple'] print(fruits.count("cherry")) # Output: 1 extend() – adds the elements of one list to the end of another list index() – returns the index of the first occurrence of a specified element in a list insert() – inserts an element at a specified index in a list pop() – removes and returns the element at a specified index in a list clear() – removes all the elements from a list my_list = [1, 2, 3] my_list.extend([4, 5]) print(my_list) # Output: [1, 2, 3, 4, 5] print(my_list.index(3)) # Output: 2 my_list.insert(1, 6) print(my_list) # Output: [1, 6, 2, 3, 4, 5] removed_element = my_list.pop(2) print(my_list) # Output: [1, 6, 3, 4, 5] print(removed_element) # Output: 2 my_list.clear() print(my_list) # Output: [] Dictionary Functions keys() – returns a list of all the keys in a dictionary values() – returns a list of all the values in a dictionary items() – returns a list of all the key-value pairs in a dictionary get() – returns the value associated with a specified key pop() – removes the key-value pair associated with a specified key person = {"name": "John", "age": 25, "country": "USA"} print(person.keys()) # Output: dict_keys(['name', 'age', 'country']) print(person.values()) # Output: dict_values(['John', 25, 'USA']) print(person.items()) # Output: dict_items([('name', 'John'), ('age', 25), ('country', 'USA')]) print(person.get("name")) # Output: John person.pop("age") print(person) # Output: {'name': 'John', 'country': 'USA'} update() - updates the keys and values in a dictionary with another dictionary or key-value pairs clear() - removes all the key-value pairs from a dictionary copy() - returns a shallow copy of a dictionary popitem() - removes and returns a random key-value pair from a dictionary person = {"name": "John", "age": 25, "country": "USA"} person2 = {"name": "Jane", "city": "New York"} person.update(person2) print(person) # Output: {'name': 'Jane', 'age': 25, 'country': 'USA', 'city': 'New York'} person.clear() print(person) # Output: {} person = person2.copy() print(person) # Output: {'name': 'Jane', 'city': 'New York'} person.popitem() print(person) # Output: {'name': 'Jane'} File Handling Functions open() – opens a file and returns a file object read() – reads the contents of a file write() – writes data to a file close() – closes a file object # Open a file file = open("example.txt", "w") # Write data to the file file.write("Hello, world!") # Close the file file.close() # Open the file again and read its contents file = open("example.txt", "r") print(file.read()) # Output: Hello, world! file.close() File Handling Functions (continued) readline() – reads a single line from a file readlines() – reads all the lines from a file and returns them as a list writelines() – writes a list of strings to a file seek() – sets the current position in a file tell() – returns the current position in a file # Open a file file = open("example.txt", "r") # Read a single line from the file line = file.readline() print(line) # Output: Hello, world! # Read all the lines from the file and return them as a list lines = file.readlines() print(lines) # Output: ['Hello, world!\\\\n', 'This is a test file.\\\\n'] # Close the file file.close() # Open the file again and write a list of strings to it file = open("example.txt", "w") file.writelines(["This is line 1.\\\\n", "This is line 2.\\\\n", "This is line 3.\\\\n"]) file.close() # Open the file again and read its contents file = open("example.txt", "r") print(file.read()) # Output: This is line 1.\\\\nThis is line 2.\\\\nThis is line 3.\\\\n file.close() # Open the file again and set the current position to the beginning of the file file = open("example.txt", "r") file.seek(0) # Read the first two characters from the file print(file.read(2)) # Output: Th # Get the current position in the file print(file.tell()) # Output: 2 # Close the file file.close() Type Conversion Functions int() – converts a string or float to an integer float() – converts a string or integer to a float str() – converts any data type to a string list() – converts any iterable to a list print(int("42")) # Output: 42 print(float("3.14")) # Output: 3.14 print(str(42)) # Output: "42" print(list("hello")) # Output: ['h', 'e', 'l', 'l', 'o'] bool() – converts a value to a Boolean (True or False) value tuple() – converts any iterable to a tuple set() – converts any iterable to a set dict() – converts a sequence of key-value pairs to a dictionary print(bool(0)) # Output: False print(bool(1)) # Output: True print(tuple("hello")) # Output: ('h', 'e', 'l', 'l', 'o') print(set([1, 2, 3, 2, 1])) # Output: {1, 2, 3} print(dict([("name", "John"), ("age", 25), ("country", "USA")])) # Output: {'name': 'John', 'age': 25, 'country': 'USA'} Input and Output Functions input() – gets input from the user print() – prints output to the console name = input("What is your name? ") print("Hello, " + name + "!")

OS Module

The OS module comes under Python’s standard utility modules. The *os* and *os.path* modules include many functions to interact with the file system.

Handling the Current Working Directory

 Getting the Current working directory

To get the location of the current working directory os.getcwd() is used. import os cwd = os.getcwd() print("Current working directory:", cwd) Output: Current working directory: /home/nikhil/Desktop/gfg

 Changing the Current working directory

To change the current working directory(CWD) os.chdir() method is used. import os def current_path(): print("Current working directory before") print(os.getcwd()) print() current_path() os.chdir('../') current_path() Output: Current working directory before C:\Users\Nikhil Aggarwal\Desktop\gfg Current working directory after C:\Users\Nikhil Aggarwal\Desktop

Creating a Directory

 Using os.mkdir()

import os directory = "GeeksforGeeks" parent_dir = "D:/Pycharm projects/" path = os.path.join(parent_dir, directory) os.mkdir(path) print("Directory '% s' created" % directory) directory = "Geeks" parent_dir = "D:/Pycharm projects" mode = 0o666 path = os.path.join(parent_dir, directory) os.mkdir(path, mode) print("Directory '% s' created" % directory) Output: Directory 'GeeksforGeeks' created Directory 'Geeks' created

 Using os.makedirs()

os.makedirs() method in Python is used to create a directory recursively. That means while making leaf directory if any intermediate-level directory is missing, os.makedirs() method will create them all. Example: This code creates two directories, “Nikhil” and “c”, within different parent directories. It uses the os.makedirs function to ensure that parent directories are created if they don’t exist. It also sets the permissions for the “c” directory. The code prints messages to confirm the creation of these directories import os directory = "Nikhil" parent_dir = "D:/Pycharm projects/GeeksForGeeks/Authors" path = os.path.join(parent_dir, directory) os.makedirs(path) print("Directory '% s' created" % directory) directory = "c" parent_dir = "D:/Pycharm projects/GeeksforGeeks/a/b" mode = 0o666 path = os.path.join(parent_dir, directory) os.makedirs(path, mode) print("Directory '% s' created" % directory) Output: Directory 'Nikhil' created Directory 'c' created

Listing out Files and Directories with Python

There is os.listdir() method in Python is used to get the list of all files and directories in the specified directory. If we don’t specify any directory, then the list of files and directories in the current working directory will be returned. Example: This code lists all the files and directories in the root directory (“/”). It uses the os.listdir function to get the list of files and directories in the specified path and then prints the results. import os path = "/" dir_list = os.listdir(path) print("Files and directories in '", path, "' :") print(dir_list) Output: Files and directories in ' / ' : ['sys', 'run', 'tmp', 'boot', 'mnt', 'dev', 'proc', 'var', 'bin', 'lib64', 'usr', 'lib', 'srv', 'home', 'etc', 'opt', 'sbin', 'media']

Deleting Directory or Files using Python

OS module proves different methods for removing directories and files in Python. These are – Using os.remove() Using os.rmdir()

 Using os.remove() Method

os.remove() method in Python is used to remove or delete a file path. This method can not remove or delete a directory. If the specified path is a directory then OSError will be raised by the method. Example: Suppose the file contained in the folder are: This code removes a file named “file1.txt” from the specified location “D:/Pycharm projects/GeeksforGeeks/Authors/Nikhil/”. It uses the os.remove function to delete the file at the specified path. import os file = 'file1.txt' location = "D:/Pycharm projects/GeeksforGeeks/Authors/Nikhil/" path = os.path.join(location, file) os.remove(path) Output:

 Using os.rmdir()

os.rmdir() method in Python is used to remove or delete an empty directory. OSError will be raised if the specified path is not an empty directory. Example: Suppose the directories are This code attempts to remove a directory named “Geeks” located at “D:/Pycharm projects/”. It uses the os.rmdir function to delete the directory. If the directory is empty, it will be removed. If it contains files or subdirectories, you may encounter an error. import os directory = "Geeks" parent = "D:/Pycharm projects/" path = os.path.join(parent, directory) os.rmdir(path) Output:

Commonly Used Functions

 Using os.name function

This function gives the name of the operating system dependent module imported. The following names have currently been registered: ‘posix’, ‘nt’, ‘os2’, ‘ce’, ‘java’ and ‘riscos’. import os print(os.name) Output: posix Note: It may give different output on different interpreters, such as ‘posix’ when you run the code here.

 Using os.error Function

All functions in this module raise OSError in the case of invalid or inaccessible file names and paths, or other arguments that have the correct type, but are not accepted by the operating system. os.error is an alias for built-in OSError exception. This code reads the contents of a file named ‘GFG.txt’. It uses a try…except block to handle potential errors, particularly the ‘IOError that may occur if there’s a problem reading the file. If an error occurs, it will print a message saying, “Problem reading: GFG.txt.” import os try: filename = 'GFG.txt' f = open(filename, 'rU') text = f.read() f.close() except IOError: print('Problem reading: ' + filename) Output: Problem reading: GFG.txt

 Using os.popen() Function

This method opens a pipe to or from command. The return value can be read or written depending on whether the mode is ‘r’ or ‘w’. Syntax: os.popen(command[, mode[, bufsize]]) Parameters mode & bufsize are not necessary parameters, if not provided, default ‘r’ is taken for mode. This code opens a file named ‘GFG.txt’ in write mode, writes “Hello” to it, and then reads and prints its contents. The use of os.popen is not recommended, and standard file operations are used for these tasks. import os fd = "GFG.txt" file = open(fd, 'w') file.write("Hello") file.close() file = open(fd, 'r') text = file.read() print(text) file = os.popen(fd, 'w') file.write("Hello") Output: Hello Note: Output for popen() will not be shown, there would be direct changes into the file.

 Using os.close() Function

Close file descriptor fd. A file opened using open(), can be closed by close()only. But file opened through os.popen(), can be closed with close() or os.close(). If we try closing a file opened with open(), using os.close(), Python would throw TypeError. import os fd = "GFG.txt" file = open(fd, 'r') text = file.read() print(text) os.close(file) Output: Traceback (most recent call last): File "C:\Users\GFG\Desktop\GeeksForGeeksOSFile.py", line 6, in os.close(file) TypeError: an integer is required (got type _io.TextIOWrapper) Note: The same error may not be thrown, due to the non-existent file or permission privilege.

 Using os.rename() Function

A file old.txt can be renamed to new.txt, using the function os.rename(). The name of the file changes only if, the file exists and the user has sufficient privilege permission to change the file. import os fd = "GFG.txt" os.rename(fd,'New.txt') os.rename(fd,'New.txt') Output: Traceback (most recent call last): File "C:\Users\GFG\Desktop\ModuleOS\GeeksForGeeksOSFile.py", line 3, in os.rename(fd,'New.txt') FileNotFoundError: [WinError 2] The system cannot find the file specified: 'GFG.txt' -> 'New.txt' A file name “GFG.txt” exists, thus when os.rename() is used the first time, the file gets renamed. Upon calling the function os.rename() second time, file “New.txt” exists and not “GFG.txt” thus Python throws FileNotFoundError.

 Using os.remove() Function

Using the Os module we can remove a file in our system using the os.remove() method. To remove a file we need to pass the name of the file as a parameter. import os #importing os module. os.remove("file_name.txt") #removing the file. The OS module provides us a layer of abstraction between us and the operating system. When we are working with os module always specify the absolute path depending upon the operating system the code can run on any os but we need to change the path exactly. If you try to remove a file that does not exist you will get FileNotFoundError.

 Using os.path.exists() Function

This method will check whether a file exists or not by passing the name of the file as a parameter. OS module has a sub-module named PATH by using which we can perform many more functions. import os #importing os module result = os.path.exists("file_name") #giving the name of the file as a parameter. print(result) Output: False As in the above code, the file does not exist it will give output False. If the file exists it will give us output True.

 Using os.path.getsize() Function

In os.path.getsize() function, python will give us the size of the file in bytes. To use this method we need to pass the name of the file as a parameter. import os #importing os module size = os.path.getsize("filename") print("Size of the file is", size," bytes.") Output: Size of the file is 192 bytes.