I.os
import os # 1. Get the absolute path to the current script. """ abs_path = (__file__) print(abs_path) """ # 2. Get the parent directory of the current file """ base_path = ( (trails) ) print(base_path) """ # 3. Path splicing """ p1 = (base_path, 'xx') print(p1) p2 = (base_path, 'xx', 'oo', '') print(p2) """ # 4. determining whether a path exists """ exists = (p1) print(exists) """ # 5. Creating folders """ (trails) """ """ path = (base_path, 'xx', 'oo', 'uuuu') if not (path): (path) """ # 6. is it a folder """ file_path = (base_path, 'xx', 'oo', '') is_dir = (file_path) print(is_dir) # False folder_path = (base_path, 'xx', 'oo', 'uuuu') is_dir = (folder_path) print(is_dir) # True """ # 7. Delete a file or folder """ ("File path") """ """ path = (base_path, 'xx') (path) """
- listdir to see all files in the directory
- walk, see all files in the directory (including descendant files)
import os """ data = ("/Users/hqss/PycharmProjects/luffyCourse/day14/commons") print(data) # ['', '__init__.py', '', '__pycache__', '', 'tencent'] """ """ To iterate over all files in a folder, e.g., to iterate over all mp4 files in a folder """ data = ("/Users/hqss/Documents/Video Tutorials/Luffy Python/mp4") for path, folder_list, file_list in data: for file_name in file_list: file_abs_path = (path, file_name) ext = file_abs_path.rsplit(".",1)[-1] if ext == "mp4": print(file_abs_path)
II. Shutil
import shutil # 1. Deletion of folders """ path = (base_path, 'xx') (path) """ # 2. Copy the folder """ ("/Users/hqss/Desktop/Graph/csdn/","/Users/hqss/PycharmProjects/CodeRepository/files") """ # 3. Copying files """ ("/Users/hqss/Desktop/Diagram/csdn/WX20201123-112406@","/Users/hqss/PycharmProjects/CodeRepository/") ("/Users/hqss/Desktop/Diagram/csdn/WX20201123-112406@","/Users/hqss/PycharmProjects/CodeRepository/") """ # 4. File or folder renaming """ ("/Users/hqss/PycharmProjects/CodeRepository/","/Users/hqss/PycharmProjects/CodeRepository/") ("/Users/hqss/PycharmProjects/CodeRepository/files","/Users/hqss/PycharmProjects/CodeRepository/images") """ # 5. compressed files """ # base_name, compressed tarball file # format, the format of the compression, e.g. "zip", "tar", "gztar", "bztar", or "xztar". # root_dir, path to the folder to be compressed """ # shutil.make_archive(base_name=r'datafile',format='zip',root_dir=r'files') # 6. Unzip the file """ # filename, the zip file to be unzipped # extract_dir, the path of the extracted file # format, compressed file format """ # shutil.unpack_archive(filename=r'', extract_dir=r'xxxxxx/xo', format='zip')
III. sys
import sys # 1. Getting the interpreter version """ print() print(sys.version_info) print(sys.version_info.major, sys.version_info.minor, sys.version_info.micro) """ # 2. Importing module paths """ print() """
- argv, the parameter passed after the python interpreter when executing a script
import sys print() # [ # '/Users/hqss/PycharmProjects/luffyCourse/day14/2.Accepting arguments for executing the script.py' # ] # [ # "2. Accept parameters for executing the script.py" # ] # ['2. Accept arguments for executing the script.py', '127', '999', '666', 'wupeiqi'] # For example, please implement a tool to download images. def download_image(url): print("Download image", url) def run(): # Accept parameters passed in by the user url_list = [1:] for url in url_list: download_image(url) if __name__ == '__main__': run()
IV. Random
import random # 1. Get a random integer in the range v = (10, 20) print(v) # 2. Get a range of random decimals v = (1, 10) print(v) # 3. A randomly selected element v = ([11, 22, 33, 44, 55]) print(v) # 4. Random selection of multiple elements v = ([11, 22, 33, 44, 55], 3) print(v) # 5. data = [1, 2, 3, 4, 5, 6, 7, 8, 9] (data) print(data)
V. Hashlib
import hashlib hash_object = hashlib.md5() hash_object.update("Wu Pei Qi".encode('utf-8')) result = hash_object.hexdigest() print(result)
import hashlib hash_object = hashlib.md5("iajfsdunjaksdjfasdfasdf".encode('utf-8')) hash_object.update("Wu Pei Qi".encode('utf-8')) result = hash_object.hexdigest() print(result)
VI. Configparser
See the address, Python reads ini configuration files using configparser, for details.https:///article/
VII. xml
See the address, python custom parsing of simple xml format files, for details.https:///article/
VIII. json
The json module, an internal python module, can convert python data format to json format, and can also convert json format data to python data format.
json format, a data format (essentially a string, commonly used for network data transfer)
# The format of data types in Python data = [ {"id": 1, "name": "Wu Pei Qi", "age": 18}, {"id": 2, "name": "alex", "age": 18}, ('wupeiqi',123), ] # JSON format value = '[{"id": 1, "name": "Wu Pei Qi", "age": 18}, {"id": 2, "name": "alex", "age": 18},["wupeiqi",123]]'
core functionality
The role of json format
Cross-language data transfer, for example:
System A is developed in Python and has list types, dictionary types, etc.
System B is developed in Java and has types of arrays, maps, etc.The underlying data type format is different for each language.
In order to facilitate the transfer of data, we agreed on a format: json format, each language is to convert their own data types to json format, but also can be converted to their own data types in json format.
Interconversion of Python data types to json format:
- Data type -> json , generally known as: serialized
import json data = [ {"id": 1, "name": "Wah Ching Shui", "age": 18}, {"id": 2, "name": "alex", "age": 18}, ] res = (data) print(res) # '[{"id": 1, "name": "\u6b66\u6c9b\u9f50", "age": 18}, {"id": 2, "name": "alex", "age": 18}]' res = (data, ensure_ascii=False) print(res) # '[{"id": 1, "name": "Wah Ching Sui Shang", "age": 18}, {"id": 2, "name": "alex", "age": 18}]''
- json format -> data type, generally known as: deserialized
import json data_string = '[{"id": 1, "name": "Wah Ching Shui", "age": 18}, {"id": 2, "name": "alex", "age": 18}]' data_list = (data_string) print(data_list)
Type Requirements
The python data type conversion to json format has requirements on the data type, which is only supported by default:
+-------------------+---------------+ | Python | JSON | +===================+===============+ | dict | object | +-------------------+---------------+ | list, tuple | array | +-------------------+---------------+ | str | string | +-------------------+---------------+ | int, float | number | +-------------------+---------------+ | True | true | +-------------------+---------------+ | False | false | +-------------------+---------------+ | None | null | +-------------------+---------------+ data = [ {"id": 1, "name": "Wu Pei Qi", "age": 18}, {"id": 2, "name": "alex", "age": 18}, ]
Other types need to be customized if they want supportJSONEncoder
can only be realized
import json from decimal import Decimal from datetime import datetime data = [ {"id": 1, "name": "Wu Pei Qi", "age": 18, 'size': Decimal("18.99"), 'ctime': ()}, {"id": 2, "name": "alex", "age": 18, 'size': Decimal("9.99"), 'ctime': ()}, ] class MyJSONEncoder(): def default(self, o): if type(o) == Decimal: return str(o) elif type(o) == datetime: return ("%Y-%M-%d") return super().default(o) res = (data, cls=MyJSONEncoder) print(res)
Other Functions
commonly used in json modules:
, serialized to generate a string.
, hair serialization generates python data types.
, serialize data and write to file (not commonly used)
import json data = [ {"id": 1, "name": "Wu Pei Qi", "age": 18}, {"id": 2, "name": "alex", "age": 18}, ] file_object = open('', mode='w', encoding='utf-8') (data, file_object) file_object.close()
-
, reads data from a file and deserializes it to a python data type (not commonly used)
import json file_object = open('', mode='r', encoding='utf-8') data = (file_object) print(data) file_object.close()
IX. TIME
import time # Get current timestamp (since 1970-1-1 00:00) v1 = () print(v1) # Time zones v2 = # Stop for n seconds before executing subsequent code. (5)
X. Datetime
Time in the usual development process is generally thought to exist in the following three formats:
- datetime
from datetime import datetime, timezone, timedelta v1 = () # Current local time print(v1) tz = timezone(timedelta(hours=7)) # Current time in Sector 7 East v2 = (tz) print(v2) v3 = () # Current UTC time print(v3)
from datetime import datetime, timedelta v1 = () print(v1) # Adding and subtracting time v2 = v1 + timedelta(days=140, minutes=5) print(v2) # datetime type + timedelta type
from datetime import datetime, timezone, timedelta v1 = () print(v1) v2 = () # Current UTC time print(v2) # Subtract between datetimes to calculate intervals (can't add) data = v1 - v2 print(, / 60 / 60, ) # datetime type - datetime type # datetime types Compare datetime types
- string (computer science)
# Time in string format ---> converted to datetime format time text = "2021-11-11" v1 = (text,'%Y-%m-%d') # %Y year, %m, month, %d, day. print(v1)
# datetime format ----> convert to string format v1 = () val = ("%Y-%m-%d %H:%M:%S") print(val)
- timestamp
# Timestamp format --> convert to datetime format ctime = () # 11213245345.123 v1 = (ctime) print(v1)
# datetime format ---> convert to timestamp format v1 = () val = () print(val)
Supplement:
- UTC/GMT: Universal Time
- Local time: the time in the local time zone.
There are two modules in Python for time processing, time and datetime.
This is the end of the summary of the 10 built-in modules commonly used in Python, and you are welcome to criticize and correct them!
This article on Python basic built-in module detailed article is introduced to this, more related Python built-in module content, please search for my previous articles or continue to browse the following related articles I hope you will support me in the future more!