Basic knowledge of Language basics Pycharm shortcut keys
Quick Copy
Cursor navigates to a row or selects many rows Crtl/command + D
Comments
The cursor navigates to a line or selects many rows Crtl/command +/
Delete (cut)
Cursor navigates to a row or selects many rows Crtl/command + D
Pycharm Simple Setup
Python template file Settings
Command +, Editor, code Style, File and Code templaates, Python Script
Interpreter modification
Command +, Project:pycharm project, Project interpreter, Project interpreter:
Installing the Python module
PS: Another way is to install via PIP.
Command +, Project:pycharm project, Project interpreter, click on the "+",-> search box to enter the module you want to install, click on the bottom left, and Insta LL Package
First Program
#!/usr/bin/env python#-*- coding:utf-8 -*-#Authour fei.wang#Date:print("hello")
Note:
1,2行为固定的写法(必须),3 4行是规范,标明作者和脚本新建时间。第1行 表示python解释器。第2行 表示脚本的编码格式。
String
Define a string
>>> name = "wangfei">>> print(name)wangfei>>> print(type(name))<class ‘str‘>
string slices
>>> name[0]‘w‘>>> name[1]‘a‘>>> name[0:]‘wangfei‘>>> name[0:4]‘wang‘
Formatting characters
>>> print("name: %s" %name)name: wangfei>>> print("name:{}".format(name))name:wangfei>>> age = 18>>> print("name:{} age:{}".format(name,age))name:wangfei age:18
String built-in functions
StartsWith
>>> cmd = "ifconfig -a">>> cmd.startswith("if")True>>> if cmd.startswith("if"):... print("ok")... ok
Endswitch
>>> cmd2 = "hellow boy">>> if cmd2.endswith("boy"):... print("ok")... else:... print("no")... ok
Replace
>>> cmd2.replace("boy","girl")‘hellow girl‘
Split cut
>>> v = "a.b.c.d.e.f">>> v.split(".")[‘a‘, ‘b‘, ‘c‘, ‘d‘, ‘e‘, ‘f‘]
Join
>>> li = v.split(".")>>> "+".join(li)‘a+b+c+d+e+f‘
List
Features: Ordered repeatable, iterative nesting
>>> li = [1,2,3,4,4]>>> li[0]1>>> li.append("5")>>> li[1, 2, 3, 4, 4, ‘5‘]>>> li.pop()‘5‘>>> li.pop()4>>> li.pop()4>>> li.pop()3 >>> li = [1,2,3,4,4]>>> for iter in li:... print(iter)... 12344
Dict
Features: unordered, key values, key unique, can be nested
>>> name = {"k1":"v1","k2":"v2","k3":"v3","k4":[1,2,3,4,5,6,7]}>>> name["k1"]‘v1‘>>> name["k4"][1, 2, 3, 4, 5, 6, 7]>>> name["k4"][0]1>>> name["k4"][-1]7>>> name["k5"]="v5">>> name{‘k5‘: ‘v5‘, ‘k2‘: ‘v2‘, ‘k4‘: [1, 2, 3, 4, 5, 6, 7], ‘k3‘: ‘v3‘, ‘k1‘: ‘v1‘}>>> del name["k5"]>>> name{‘k2‘: ‘v2‘, ‘k4‘: [1, 2, 3, 4, 5, 6, 7], ‘k3‘: ‘v3‘, ‘k1‘: ‘v1‘}>>> name["k5"]Traceback (most recent call last): File "<stdin>", line 1, in <module>KeyError: ‘k5‘>>> for k in name:... print("key:{},values:{}".format(k,name[k]))... key:k2,values:v2key:k4,values:[1, 2, 3, 4, 5, 6, 7]key:k3,values:v3key:k1,values:v1
Conditional judgment
If
num = 3if num > 2 : print("{} > 2".format(num))else: print("{} < 2".format(num))例子:import oscmd = "ifconfig -a"if cmd.startswith("rm"): print("forbid command.")else: os.system(cmd)
Cycle
For
for num in range(9):print(num)# break 中止循环for num in range(9): if num > 8: break print(num)# continue 跳出本层循环 for num in range(9):if num == 8: continueprint(num)
While
import timewhile True: time.sleep(2) print("aaa")
Data structure functions
Definition and execution of functions
def func(): print("hellow")func()
return value of the function
def func(): print("hellow") return "hellow"# 默认返回是Nonere = func()print(re)
Local variables and global variables
num = 10 # 全局变量def func(): num = 1 # 局部变量 print("hellow")func()
To pass parameters to a function.
# 形式参数def func(name,age): print("name {},age {}".format(name,age))func("wf","18")# 默认参数def func(name,age=18): print("name {},age {}".format(name,age))func("wf","27")# 位置参数def func(name,age=18): print("name {},age {}".format(name,age))func(age = 18,name = "wf")# 传入多参数def func(*args):print(args)for Iter in args: print(Iter)li = [1,2,3,4,5] func(*li)# 传入key values def func(**kwargs):print(kwargs["name"],kwargs["age"])msg = {"name":"wf","age":18}func(**msg) # 万能参数def func(*args,**kwargs):print(‘‘‘args:{}kwargs:{}‘‘‘.format(args,kwargs))li = [1,2,3,4]msg = {"name":"wf","age":18}func(*li,**msg)
File Cleanup Scripts
import osdef remove_file(path,tag):for Iter in os.walk(path): for file in Iter[-1]: file_abspath = Iter[0] + "/" + file if file_abspath.endswith("txt"): print("remove file:{}".format(file_abspath)) #os.remove(file_abspath)if __name__ == "__main__":# path = input("path:> ")path = "/Users/feiwang/PycharmProjects/python-study2/work/test"# tag = input("tag")tag = "txt"remove_file(path,tag)
Decorative Device
def f0(func): def wrapper(*args,**kwargs): print("hello") func() print("bye") return wrapper@f0def f1(): print("my name is wf.")f1()
Module
Import Module
import 模块from 模块 import 方法 from 文件夹路径.模块 import 方法from 文件夹路径.模块 import 方法 as 别名
Json
Serialization deserialization
import jsondic = { "name":"wf", "age":"18", "sex":"man", "salary":20000, "interest":["read", "game", "music"],}re = json.dumps(dic) # 序列化;把字典变成字符串print(type(re))dic2 = json.loads(re) # 反序列化;把字符串变成字典print(type(dic2))
Example:
Use requests to get JSON-formatted data from the API interface and deserialize it.
import requestsimport jsonpara = {‘token‘: ‘HPcWR7l4NJNJ‘, ‘name‘: ‘adminset‘}# 参数拼接r = requests.get("http://115.28.147.154/cmdb/get/host/", params = para)data = r.textprint(r.url) # 显示拼接的urld1 = json.loads(data)print(type(d1))
File operations
File open Mode Reference link
Open directly
file = open("url_list.txt","r")# re = file.read # 读取文件所有行# re = file.readline() # 一行一行的读取文件内容re = file.readlines() # 读取所有的文件内容,返回的是一个列表print(re)file.close()
With context processing (recommended)
with open("url_list.txt","r") as file: # re = file.read # 读取文件所有行 # re = file.readline() # 一行一行的读取 re = file.readlines() # 读取文件的所有行,返回的是一个列表 print(re)
Liezi:
The content of a log file is processed and the processed content is placed separately into a file.
Requirement: Each time it is opened, it should be processed at the last content location instead of starting from scratch.
from time import ctimeimport osimport timetag = 0while True: with open("url_list.txt","rb+") as file ,open("url_list.log","ab+") as log_file: file.seek(tag) # 挪动文件指针,到指定位置 while True: line = file.readline() if line: new_line = str(ctime()) + " - " + str(line,encoding="utf-8") print(new_line) log_file.write(bytes(new_line,encoding="utf-8")) else: break tag = file.tell() # 获取文件指针位置 time.sleep(2) print("-"*50)
Python knowledge Simple Summary-language Foundation (i)