我的Python学习之路,从入门到实战
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了我的Python学习之路,从入门到实战相关的知识,希望对你有一定的参考价值。
Python 学习手册
【学习线路】
【学习线路图】
【技能对照表】
一、容器
- 列表(list)
- 元组(tuple)
- 集合(set)
- 字典(dict)
1、列表
线性表:
- 数组:连续内存的实现
- 栈:先进后出,后进先出
- 队列:先进先出,后进后出
- 链表:
- 单向链表:尾指针指向首地址
- 双向链表:收尾指向
- [ ] Python 没有数组,数组查询速度快,增删改查效率慢
- [ ] Python 的列表是基于双向链表实现,列表查询速度慢,增删改查速度快。
- [ ] 列表底层是基于双向链表实现的,里面的元素的有序的、可以重复的。
(1)列表的定义
# 若数据类型语言
>>> ls = [1, 2, zhangwanqiang, man]
>>> type(ls)
<class list>
>>> ls
[1, 2, zhangwanqiang, man]
# 全局函数
>>> ls1 = list([zhangwanqiag, 18, man])
>>> type(ls1)
<class list>
>>> ls1
[zhangwanqiag, 18, man]
(2)元素的访问
>>> ls1
[zhangwanqiag, 18, man]
>>> ls[1]
2
>>> ls1[2]
man
全局函数:
>>> ls1[2]
man
>>> len(ls)
4
>>> len(ls1)
3
(3)遍历列表
>>> for i in ls:
... print(i)
...
1
2
zhangwanqiang
man
>>>
>>>
>>> index = 0
>>> while index < len(ls):
... print(ls[index])
... index += 1
...
1
2
zhangwanqiang
man
(4)列表的常见方法
--- append # 列表尾部插入元素
>>> ls
[1, 2, zhangwanqiang, 1]
>>> ls.append(man)
>>> ls
[1, 2, zhangwanqiang, 1, man]
--- insert # 指定位置插入元素
>>> ls
[1, 2, zhangwanqiang, 1, man]
>>> ls.insert(2, good)
>>> ls
[1, 2, good, zhangwanqiang, 1, man]
--- sort # 对列表元素进行排序
>>> ls2 = [21, 45, 32, 100]
>>> ls3 = [s, k, r, s, a, g]
>>> ls2.sort()
>>> ls3.sort()
>>> ls2
[21, 32, 45, 100]
>>> ls3
[a, g, k, r, s, s]
--- index # 查看指定元素索引位置
>>> ls
[1, 2, good, zhangwanqiang, 1, man]
>>> ls.index(1)
0
--- reverse # 反转列表元素
>>> ls
[1, 2, good, zhangwanqiang, 1, man]
>>> ls.reverse()
>>> ls
[man, 1, zhangwanqiang, good, 2, 1]
--- remove # 移除指定元素
>>> ls
[man, 1, zhangwanqiang, good, 2, 1]
>>> ls.remove(good)
>>> ls
[man, 1, zhangwanqiang, 2, 1]
--- count # 统计列表元素个数
>>> ls
[man, 1, zhangwanqiang, 2, 1]
>>> ls.count(1)
2
--- clear # 清除列表
>>> ls1
[zhangwanqiag, 18, man]
>>> ls1.clear()
>>> ls1
[]
--- copy # 浅拷贝
>>> ls
[man, 1, zhangwanqiang, 2, 1]
>>> ls10 = ls.copy()
>>> ls10
[man, 1, zhangwanqiang, 2, 1]
>>> ls.append(123456)
>>> ls
[man, 1, zhangwanqiang, 2, 1, 123456]
>>> ls10
[man, 1, zhangwanqiang, 2, 1]
--- extend # 合并列表
>>> ls2
[21, 32, 45, 100]
>>> ls3
[a, g, k, r, s, s]
>>> ls2.extend(ls3)
>>> ls2
[21, 32, 45, 100, a, g, k, r, s, s]
>>> ls3
[a, g, k, r, s, s]
--- 删除最后一个元素
>>>
>>> ls3
[a, g, k, r, s, s]
>>> ls3.pop()
s
>>> ls
[man, 1, zhangwanqiang, 2, 1, 123456]
2、元组
元组的特点:
- 有序的、可重复的。
- 固定的,一旦定义了元素不可改变。
(1)元组的创建
--- 若数据类型语言
>>> t = (1, 2, 3, zhang)
>>> type(t)
<class tuple>
--- 全局函数
>>> tt = tuple((1,45,76, wan, qiang))
>>> type(tt)
<class tuple>
(2)常见方法
>>> t
(1, 2, 3, zhang)
--- index # 查看元素的索引位置
>>> t.index(3)
2
---- count # 查看元素的个数
>>> t.count(1)
1
3、集合
- [ ] 集合底层是基于hash表实现的,里面的元素是唯一的、无序的。
(1)集合的创建
--- 若数据类型
s = set(1, 3, zhang, 34)
>>> type(s)
<class set>
--- 全局函数
>>> ss = 22, wan
>>> type(ss)
<class set>
(2)集合的常见方法
--- clear # 清除集合中的元素
--- remove # 移除集合中指定的元素
--- copy # 浅拷贝
--- add # 集合中插入元素
>>> s
1, 34, 3, zhang
>>> s.add(10101)
>>> s
1, 34, 3, zhang, 10101
--- difference # 差集
>>> s
1, 34, 3, 2, zhang, 10101
>>> ss
1, 2, 3, 22, wan
>>> ss.difference(s)
wan, 22
--- intersection # 交集
>>> s
1, 34, 3, 2, zhang, 10101
>>> ss
1, 2, 3, 22, wan
>>> ss.intersection(s)
1, 2, 3
--- union # 并集
>>> s
1, 34, 3, 2, zhang, 10101
>>> ss
1, 2, 3, 22, wan
>>> ss.union(s)
1, 2, 3, 34, zhang, 10101, 22, wan
--- 合并元素
>>> s
1, 34, 3, 2, zhang, 10101
>>> ss
1, 2, 3, 22, wan
>>> s.update(ss)
>>> s
1, 34, 3, 2, zhang, 10101, 22, wan
>>> ss
1, 2, 3, 22, wan
--- 移除元素
>>> s
1, 34, 3, 2, zhang, 10101, 22, wan
>>> s.discard(wan)
>>> s
1, 34, 3, 2, zhang, 10101, 22
>>> s.discard(wan)
>>> s
1, 34, 3, 2, zhang, 10101, 22
4、字典
特点:
- 键值对的方式存储
(1)字典的创建
--- 若数据类型
>>> d = name:z3, age:17, gender:man
>>> type(d)
<class dict>
--- 全局函数
>>> dd = dict(name:lisi, age:16, gender:g)
>>> type(dd)
<class dict>
(2)元素的访问
>>> d[name]
z3
(3)常见方法
--- clean # 清除元素
--- copy # 浅拷贝
--- get # 返回key对应的值
>>> d
name: 456, age: 17, gender: man, niu: 666
>>> d.get(name)
456
--- keys # 返回所有的键
>>> d
name: 456, age: 17, gender: man, niu: 666
>>> d.keys()
dict_keys([name, age, gender, niu])
--- values # 返回所有的值
>>> d
name: 456, age: 17, gender: man, niu: 666
>>> d.values()
dict_values([456, 17, man, 666])
--- items # 返回一个键值对
>>> d
name: 456, age: 17, gender: man, niu: 666
>>> d.items()
dict_items([(name, 456), (age, 17), (gender, man), (niu, 666)])
--- pop # 删除key对应的键值对
>>> d
name: 456, age: 17, gender: man, niu: 666
>>> d.pop(gender)
man
>>> d
name: 456, age: 17, niu: 666
--- popitem # 移除一个键值对,移除规则是(LIFO)
name: 456, age: 17, niu: 666
>>> d.popitem()
(niu, 666)
>>> d
name: 456, age: 17
(4)遍历元素
--- 方法一
>>> d
name: 456, age: 17
name: 456, age: 17
>>> for key in d:
... print(key, d.get(key))
...
name 456
age 17
--- 方法二
>>> d
name: 456, age: 17
>>> for key in d.keys():
... print(key, d.get(key))
...
name 456
age 17
--- 方法三
>>> d
name: 456, age: 17
>>> for k, v in d.items():
... print(k, v)
...
name 456
age 17
二、字符串
1、字符串的创建
--- 弱数据类型
>>> s = hello python
>>> type(s)
<class str>
>>> ss = "i am zhangwanqiang"
>>> type(ss)
<class str>
>>> sss = """i am a boy"""
>>> type(sss)
<class str>
--- 全局函数
>>> ssss = str("this is a string")
>>> type(ssss)
<class str>
2、字符串的常见方法
>>> ss
i am zhangwanqiang
>>> dir(ss)
[capitalize, casefold, center, count, encode, endswith, expandtabs, find, format, format_map, index, isalnum, isalpha, isascii, isdecimal, isdigit, isidentifier, islower, isnumeric, isprintable, isspace, istitle, isupper, join, ljust, lower, lstrip, maketrans, partition, replace, rfind, rindex, rjust, rpartition, rsplit, rstrip, split, splitlines, startswith, strip, swapcase, title, translate, upper, zfill]
--- capitalize # 首字母大写
>>> ss
i am zhangwanqiang
>>> ss.capitalize()
I am zhangwanqiang
--- center #字符串居中
>>> ss
i am zhangwanqiang
>>> ss.center(100, "8")
88888888888888888888888888888888888888888i am zhangwanqiang88888888888888888888888888888888888888888
--- strip # 取出字符串两侧的空格
>>> ss
hello python
>>> ss.strip()
hello python
--- lstrip # 字符串左对齐
>>> ss
hello python
>>> ss.lstrip()
hello python
--- rstrip # 字符串右对齐
>>> ss
hello python
>>> ss.rstrip()
hello python
--- count # 统计字符或者字符串出现的个数
>>> ss
i am zhangwanqiang
>>> ss.count("a")
4
--- endswith # 判断字符或者字符串是否在字符串尾部
>>> ss
i am zhangwanqiang
>>> ss.endswith("ang")
True
>>> ss.endswith("wan")
False
--- startswith 判断字符或者字符串是否在字符串首部
>>> ss
i am zhangwanqiang
>>> ss.startswith("i")
True
>>> ss.startswith("an")
False
>>> ss.startswith("am")
False
--- index、rindex # 返回字符或者字符串的索引位置(不存在抛出异常)
>>> ss
i am zhangwanqiang
>>> ss.index("a")
2
>>> ss.rindex("a")
15
--- find、rfind # 返回字符或者字符串的索引位置(不存在返回-1)
>>> ss
i am zhangwanqiang
>>> ss.find("a")
2
>>> ss.rfind("a")
15
--- encode # 将字符串转换为字节
>>> ss
i am zhangwanqiang
>>> tt = ss.encode("utf-8")
>>> tt
bi am zhangwanqiang
>>> type(tt)
<class bytes>
# 字节转换为字符串
>>> tt
bi am zhangwanqiang
>>> type(tt)
<class bytes>
>>> dd = tt.decode("utf-8")
>>> dd
i am zhangwanqiang
>>> type(dd)
<class str>
--- format # 格式化字符串
>>> num1 = 123
>>> num2 = 321
>>> print("num = , num = ".format(num1, num2))
num = 123, num = 321
--- islower # 判断字符串是否为小写字母
>>> s
abcde
>>> ss
ABCDE
>>> s.islower()
True
>>> ss.islower()
False
--- isupper # 判断字符串是否为大写字母
>>> s
abcde
>>> ss
ABCDE
>>> s.isupper()
False
>>> ss.isupper()
True
--- istitle # 判断字符串是否为标题
>>> aa
This Is A Boy
>>> aa.istitle()
True
--- isdigit # 判断字符串是否为数字
>>> bb = 123456
>>> bb.isdigit()
True
--- isalpha # 判断字符串是否为字母
>>> s
abcde
>>> s.isalpha()
True
--- isalnum # 判断字符串是否为有效符号
>>> s
abcde
>>> ss
xs23ecc3*^%
>>> s.isalnum()
True
>>> ss.isalnum()
False
--- isspace # 判断字符串是否为空格
>>> aa
This Is A Boy
>>> bb
>>> aa.isspace()
False
>>> bb.isspace()
True
--- title # 将字符串转换为标题
>>> aa
i am a boy
>>> aa.title()
I Am A Boy
--- 将字符串转换为大写
>>> aa
i am a boy
>>> aa.upper()
I AM A BOY
--- 将字符串转换为小写
>>> bb
THIA IA A NUM
>>> bb.lower()
thia ia a num
--- split # 将字符串切成列表
i am a good boy
>>> aa.split( )
[i, am, a, good, boy]
--- join # 将可迭代对象拼接成字符串
>>> bb
[i, am, a, good, boy]
>>> .join(bb)
i am a good boy
--- 替换字符串中的字符串
>>> aa
i am a good boy
>>> aa.replace(boy, girl)
i am a good girl
3、字符串的切片
>>> ls
[112, 3, good, yesr, 242, True]
>>> ls[3:]
[yesr, 242, True]
>>> ls
[112, 3, good, yesr, 242, True]
>>> ls[1:4]
[3, good, yesr]
>>> ls
[112, 3, good, yesr, 242, True]
>>> ls[1:5:2]
[3, yesr]
>>> ls
[112, 3, good, yesr, 242, True]
>>> ls[::-1]
[True, 242, yesr, good, 3, 112]
>>> ls
[112, 3, good, yesr, 242, True]
>>> ls[-1:-5:-1]
[True, 242, yesr, good]
使用切片去切割数据,如果超越了下标不会报错,会返回一个空列表[]
练习:
已知一个字符串路径,如:D:\\\\上课.视频\\\\python\\\\Python.脱产班\\\\01.Python的环境安装.mp4请使用字符串和切片技术奖该路径的文件后缀名取出来。
--- 方法一
>>> ll
D:\\\\上课.视频\\\\python\\\\Python.脱产班\\\\01.Python的环境安装.mp4
>>> tt = ll.split()
>>> tt
[D:\\\\上课, 视频\\\\python\\\\Python, 脱产班\\\\01, Python的环境安装, mp4]
>>> tt[len(tt) -1]
mp4
--- 方法二
>>> ll
D:\\\\上课.视频\\\\python\\\\Python.脱产班\\\\01.Python的环境安装.mp4
>>> ll[ll.rfind(".") +1:]
mp4
三、全局函数
>>> import builtins
>>> dir(builtins)
[abs, all, any, ascii, bin, bool, breakpoint, bytearray, bytes, callable, chr, classmethod, compile, complex, copyright, credits, delattr, dict, dir, divmod, enumerate, eval, exec, exit, filter, float, format, frozenset, getattr, globals, hasattr, hash, help, hex, id, input, int, isinstance, issubclass, iter, len, license, list, locals, map, max, memoryview, min, next, object, oct, open, ord, pow, print, property, quit, range, repr, reversed, round, set, setattr, slice, sorted, staticmethod, str, sum, super, tuple, type, vars, zip]
四、系统内置模块
常见的模块
- random
- math
- datetime
- time
- os
- os.path
- sys
- hashlib
- hmac ... ...
模块的导入
>>> import os
>>> import hashlib [as hash]
>>> import http.server [as ser]
>>> from http import client [as cli]
1、random
作用:产生随机数
>>> import random
>>> dir(random)
[betavariate, choice, choices, expovariate, gammavariate, gauss, getrandbits, getstate, lognormvariate, normalvariate, paretovariate, randint, random, randrange, sample, seed, setstate, shuffle, triangular, uniform, vonmisesvariate, weibullvariate]
>>> random.randint(5, 10) # 产生5--10之间的整数
8
>>> random.random() # 产生0--1之间的整数
0.2718111326910797
>>> random.uniform(5, 10) # 产生一个范围的正态分布的数
7.911538309334022
>>> ls = [hello, 123, True, 4533]
>>> random.choice(ls) # 在序列(seq)中随机筛选一个元素
hello
2、math
作用:用于数学计算
>>> import math
>>> dir(math)
[acos, acosh, asin, asinh, atan, atan2, atanh, ceil, comb, copysign, cos, cosh, degrees, dist, e, erf, erfc, exp, expm1, fabs, factorial, floor, fmod, frexp, fsum, gamma, gcd, hypot, inf, isclose, isfinite, isinf, isnan, isqrt, ldexp, lgamma, log, log10, log1p, log2, modf, nan, perm, pi, pow, prod, radians, remainder, sin, sinh, sqrt, tan, tanh, tau, trunc]
>>> math.ceil(3.0000000001) # 向上取整
4
>>> math.floor(3.0000000001) # 向下取整
3
>>> math.fabs(-7) # 求绝对值
7.0
>>> math.fmod(10, 3) # 求模
1.0
>>> math.isnan(1) # 判断一个数不是数字
False
>>> math.isfinite(5) # 判断是否为数字(整数/浮点数,有限,无限或NaN),则返回True既不是无穷大也不是NaN(不是数字),否则返回False
True
>>> math.isfinite(math.e)
True
>>> math.pi # 取圆周率
3.141592653589793
>>> math.e # 自然常数
2.718281828459045
>>> math.pow(2, 3) # 幂次方运算
8.0
>>> math.sqrt(7) # 开平方根
2.6457513110645907
3、os
作业:操作系统文件系统
>>> dir(os)
[abc, abort, access, add_dll_directory, altsep, chdir, chmod, close, closerange, cpu_count, curdir, defpath, device_encoding, devnull, dup, dup2, environ, error, execl, execle, execlp, execlpe, execv, execve, execvp, execvpe, extsep, fdopen, fsdecode, fsencode, fspath, fstat, fsync, ftruncate, get_exec_path, get_handle_inheritable, get_inheritable, get_terminal_size, getcwd, getcwdb, getenv, getlogin, getpid, getppid, isatty, kill, linesep, link, listdir, lseek, lstat, makedirs, mkdir, name, open, pardir, path, pathsep, pipe, popen, putenv, read, readlink, remove, removedirs, rename, renames, replace, rmdir, scandir, sep, set_handle_inheritable, set_inheritable, spawnl, spawnle, spawnv, spawnve, st, startfile, stat, stat_result, statvfs_result, strerror, supports_bytes_environ, supports_dir_fd, supports_effective_ids, supports_fd, supports_follow_symlinks, symlink, sys, system, terminal_size, times, times_result, truncate, umask, uname_result, unlink, urandom, utime, waitpid, walk, write]
>>> os.system(cls) # 执行操作系统命令
0
>>> os.curdir # 返回当前目录(相对)
.
>>> os.path.abspath(os.curdir) # 返回当前目录(绝对)
C:\\\\Windows\\\\system32
>>> os.chdir("C:\\\\ProgramData\\\\NVIDIA") # 切换工作目录
>>> os.path.abspath(os.curdir)
C:\\\\ProgramData\\\\NVIDIA
>>> os.cpu_count() # 统计计算机cpu线程数
8
>>> os.getcwd() # 返回当前绝对路径
C:\\\\ProgramData\\\\NVIDIA
getpid() # 获取当前进程的进程编号
getppid() # 获取当前进程的父进程的编程
kill() # 通过进程编号杀死进程
>>> os.linesep # 查看操作系统换行符
\\r\\n
>>> os.listdir() # 查看当前目录下文件夹以及文件
[.jetbrains, AccountPictures, Desktop, desktop.ini, Documents, Downloads, Foxit Software, Libraries, Music, Nwt, Pictures, SogouInput, Thunder Network, Videos]
>>> os.mkdir("C:\\\\Users\\\\Public\\\\wan") # 创建目录,仅支持创建一层目录
>>> os.makedirs("C:\\\\Users\\\\Public\\\\wan\\\\a\\\\b\\\\c\\\\d") # 创建目录,仅支持递归创建
open() # 打开文件
>>> os.pathsep # 查看系统环境变量分隔符
;
>>> os.sep # 查看系统路径的分隔符
\\\\
>>> os.remove("wan.txt") # 删除指定文件
>>> os.removedirs(wan) # 删除指定目录(支持多级删除)
4、os.path
作用:用于获取文件的属性
>>> import os.path as p
>>> dir(p)
[abspath, altsep, basename, commonpath, commonprefix, curdir, defpath, devnull, dirname, exists, expanduser, expandvars, extsep, genericpath, getatime, getctime, getmtime, getsize, isabs, isdir, isfile, islink, ismount, join, lexists, normcase, normpath, os, pardir, pathsep, realpath, relpath, samefile, sameopenfile, samestat, sep, split, splitdrive, splitext, stat, supports_unicode_filenames, sys]
>>> p.abspath(.) # 返回路径的绝对路径
C:\\\\Users\\\\DELL
>>> p.realpath(.) # 返回路径的绝对路径
C:\\\\Windows\\\\System32
>>> help(p.altsep) # 用来查看python中各种符号
Operator precedence
*******************
The following table summarizes the operator precedence in Python, from
lowest precedence (least binding) to highest precedence (most
binding). Operators in the same box have the same precedence. Unless
the syntax is explicitly given, operators are binary. Operators in
the same box group left to right (except for exponentiation, which
groups from right to left).
Note that comparisons, membership tests, and identity tests, all have
the same precedence and have a left-to-right chaining feature as
described in the Comparisons section.
+-------------------------------------------------+---------------------------------------+
| Operator | Description |
|=================================================|=======================================|
| ":=" | Assignment expression |
+-------------------------------------------------+---------------------------------------+
| "lambda" | Lambda expression |
+-------------------------------------------------+---------------------------------------+
| "if" – "else" | Conditional expression |
+-------------------------------------------------+---------------------------------------+
| "or" | Boolean OR |
+-------------------------------------------------+---------------------------------------+
| "and" | Boolean AND |
+-------------------------------------------------+---------------------------------------+
| "not" "x" | Boolean NOT |
+-------------------------------------------------+---------------------------------------+
| "in", "not in", "is", "is not", "<", "<=", ">", | Comparisons, including membership |
| ">=", "!=", "==" | tests and identity tests |
+-------------------------------------------------+---------------------------------------+
| "|" | Bitwise OR |
+-------------------------------------------------+---------------------------------------+
| "^" | Bitwise XOR |
+-------------------------------------------------+---------------------------------------+
| "&" | Bitwise AND |
+-------------------------------------------------+---------------------------------------+
| "<<", ">>" | Shifts |
+-------------------------------------------------+---------------------------------------+
| "+", "-" | Addition and subtraction |
+-------------------------------------------------+---------------------------------------+
| "*", "@", "/", "//", "%" | Multiplication, matrix |
| | multiplication, division, floor |
| | division, remainder [5] |
+-------------------------------------------------+---------------------------------------+
| "+x", "-x", "~x" | Positive, negative, bitwise NOT |
+-------------------------------------------------+---------------------------------------+
| "**" | Exponentiation [6] |
+-------------------------------------------------+---------------------------------------+
| "await" "x" | Await expression |
+-------------------------------------------------+---------------------------------------+
| "x[index]", "x[index:index]", | Subscription, slicing, call, |
| "x(arguments...)", "x.attribute" | attribute reference |
+-------------------------------------------------+---------------------------------------+
| "(expressions...)", "[expressions...]", "key: | Binding or parenthesized expression, |
| value...", "expressions..." | list display, dictionary display, set |
| | display |
+-------------------------------------------------+---------------------------------------+
... ...
>>> p.basename(E:\\\\openlab--Training\\\\Python--刘建宏\\\\3.26\\\\遍历磁盘.py) # 获取文件名
遍历磁盘.py
>>> p.dirname(E:\\\\openlab--Training\\\\Python--刘建宏\\\\3.26\\\\遍历磁盘.py) # 获取路径
E:\\\\openlab--Training\\\\Python--刘建宏\\\\3.26
>>> p.curdir # 返回相对路径
.
>>> p.exists(E:\\\\openlab--Training\\\\Python--刘建宏\\\\3.26\\\\遍历磁盘.py) # 判断目录或者文件是否存在
True
>>> p.getctime(E:\\\\openlab--Training\\\\Python--刘建宏\\\\3.26\\\\遍历磁盘.py) # 获取文件的创建时间
1585210654.3121617
>>> p.getmtime(E:\\\\openlab--Training\\\\Python--刘建宏\\\\3.26\\\\遍历磁盘.py) # 获取文件内容修改时间
1585210653.45535
>>> p.getatime(E:\\\\openlab--Training\\\\Python--刘建宏\\\\3.26\\\\遍历磁盘.py) # 获取文件的元数据修改时间
1627211302.8820622
>>> p.getsize(E:\\\\openlab--Training\\\\Python--刘建宏\\\\3.26\\\\遍历磁盘.py) # 获取文件或者文件夹字节大小
684
>>> p.isdir(E:\\\\openlab--Training\\\\Python--刘建宏\\\\3.26\\\\) # 判断是否为目录
True
>>> p.isfile(E:\\\\openlab--Training\\\\Python--刘建宏\\\\3.26\\\\遍历磁盘.py) # 判断是否为文件
True
>>> p.isabs(E:\\\\openlab--Training\\\\Python--刘建宏\\\\3.26\\\\) # 判断是否为绝对路径
True
islink # 判断是否为链接文件
ismount # 判断是否为挂载文件
>>> file_name = wan.txt # 拼接文件路径和文件名
>>> url = c:/user/system/info/
>>> p.join(url, file_name)
c:/user/system/info/wan.txt
>>> p.sep # 查看路径分隔符
\\\\
>>> p.split(E:\\\\openlab--Training\\\\Python--刘建宏\\\\3.26\\\\遍历磁盘.py) # 返回文件的路径和文件名(元组)
(E:\\\\openlab--Training\\\\Python--刘建宏\\\\3.26, 遍历磁盘.py)
练习
import os
from os import path
def scanner_file(url):
files = os.listdir(url)
for f in files:
# real_path = url + "\\\\" + f
# real_path = path.join(url, f)
real_path = path.join(url, f)
if path.isfile(real_path):
print(path.abspath(real_path))
elif path.isdir(real_path):
scanner_file(real_path)
else:
print("其他情况")
scanner_file("D:\\\\软件安装包")
5、sys
作用:提供了许多函数和变量来处理 Python 运行时环境的不同部分
>>> import sys
>>> dir(sys)
[addaudithook, api_version, argv, audit, base_exec_prefix, base_prefix, breakpointhook, builtin_module_names, byteorder, call_tracing, callstats, copyright, displayhook, dllhandle, dont_write_bytecode, exc_info, excepthook, exec_prefix, executable, exit, flags, float_info, float_repr_style, get_asyncgen_hooks, get_coroutine_origin_tracking_depth, getallocatedblocks, getcheckinterval, getdefaultencoding, getfilesystemencodeerrors, getfilesystemencoding, getprofile, getrecursionlimit, getrefcount, getsizeof, getswitchinterval, gettrace, getwindowsversion, hash_info, hexversion, implementation, int_info, intern, is_finalizing, maxsize, maxunicode, meta_path, modules, path, path_hooks, path_importer_cache, platform, prefix, ps1, ps2, pycache_prefix, set_asyncgen_hooks, set_coroutine_origin_tracking_depth, setcheckinterval, setprofile, setrecursionlimit, setswitchinterval, settrace, stderr, stdin, stdout, thread_info, unraisablehook, version, version_info, warnoptions, winver]
>>> sys.api_version # 查看Python内部版本号
1013
>>> sys.argv # 接受脚本参数,第一个参数是脚本名(类似于shell位置变量)
[]
>>> sys.copyright # 查看Python版权信息
Copyright (c) 2001-2020 Python Software Foundation.\\nAll Rights Reserved.\\n\\nCopyright (c) 2000 BeOpen.com.\\nAll Rights Reserved.\\n\\nCopyright (c) 1995-2001 Corporation for National Research Initiatives.\\nAll Rights Reserved.\\n\\nCopyright (c) 1991-1995 Stichting Mathematisch Centrum, Amsterdam.\\nAll Rights Reserved.
>>> sys.exit() # 退出系统
C:\\Windows\\system32>
>>> sys.getdefaultencoding() # 获取解释器编码
utf-8
>>> sys.getfilesystemencoding() # 获取文件系统编码
utf-8
>>> sys.getrecursionlimit() # 获取Python递归限制层数(默认1000层)
1000
>>> sys.setrecursionlimit(8000) # 设置Python递归限制层数
>>> sys.getrecursionlimit()
8000
>>> s = [1, 2, 3, 4] # 获取Python对象的引用计数
>>> sys.getrefcount(s)
2
>>> ss = s
>>> sys.getrefcount(s)
3
>>> sys.getwindowsversion() # 获取窗口大小
sys.getwindowsversion(major=10, minor=0, build=18363, platform=2, service_pack=)
>>> sys.version # 获取Python版本信息
3.8.2 (tags/v3.8.2:7b3ab59, Feb 25 2020, 23:03:10) [MSC v.1916 64 bit (AMD64)]
>>> sys.version_info # 获取Python版本信息
sys.version_info(major=3, minor=8, micro=2, releaselevel=final, serial=0)
Python的垃圾回收原理:引用计数为主,以标记清除和分带收集为辅
6、hashlib
作用:hash加密
算法分类:
按照算法是否可逆分类
- 可逆算法
- 对称加密算法
加密与解密使用同一把秘钥
DES
SEDS
AES
IDEA - 非对称加密算法
加密与解密使用不同的秘钥(公钥/私钥)
RSA
DH
DSA
EC
- 非可逆算法
特地:不可逆行、唯一性、雪崩效应
- hash
MD5
SHA
HMAC
>>> import hashlib
>>> dir(hashlib)
[__all__, __block_openssl_constructor, __builtin_constructor_cache, __builtins__, __cached__, __doc__, __file__, __get_builtin_constructor, __loader__, __name__, __package__, __spec__, _hashlib, algorithms_available, algorithms_guaranteed, blake2b, blake2s, md5, new, pbkdf2_hmac, scrypt, sha1, sha224, sha256, sha384, sha3_224, sha3_256, sha3_384, sha3_512, sha512, shake_128, shake_256]
# hash 加密使用方法:
>>> md5 = hashlib.md5("hello python".encode("utf-8"))
>>> md5
<md5 HASH object @ 0x00000154A70C7C10>
>>> md5.hexdigest()
e53024684c9be1dd3f6114ecc8bbdddc
# 使用update颜值混淆加密
>>> md5 = hashlib.md5("hello python".encode("utf-8"))
>>> md5.hexdigest()
e53024684c9be1dd3f6114ecc8bbdddc
>>> md5.update("xnudsy832d0ws2h*&^$%$%VY&".encode("utf-8"))
>>> md5.hexdigest()
f2da0a61a7e483d9b1df742958eb0244
应用:
- 数据校验,安全检查 ---- 不需要做盐值混淆
- 数据库传输 ---- 需要做盐值混淆
注意:hashlib中所有hash算法操作方法雷同
用途:数字摘要,密码信息加密
7、hmac
作用:对称加密 + hash加密
>>> import hmac
>>> dir(hmac)
[HMAC, __builtins__, __cached__, __doc__, __file__, __loader__, __name__, __package__, __spec__, _hashlib, _hashopenssl, _openssl_md_meths, _warnings, compare_digest, digest, digest_size, new, trans_36, trans_5C]
# 先进行对称加密,在进行MD5加密
>>> hmac = hmac.new("123456".encode("utf-8"), "zhangwanqiang".encode("utf-8"), "MD5")
>>> hmac.hexdigest()
eb4ee22adc6a3f77696703f21d65ac07
用途:密码信息加密(安全性较高)
8、time
作用:时间相关
>>> import time
>>> dir(time)
[_STRUCT_TM_ITEMS, __doc__, __loader__, __name__, __package__, __spec__, altzone, asctime, ctime, daylight, get_clock_info, gmtime, localtime, mktime, monotonic, monotonic_ns, perf_counter, perf_counter_ns, process_time, process_time_ns, sleep, strftime, strptime, struct_time, thread_time, thread_time_ns, time, time_ns, timezone, tzname]
>>> time.asctime() # 获取当前时间
Tue Jul 27 16:54:56 2021
>>> time.ctime() # 获取当前时间
Tue Jul 27 17:16:23 2021
>>> time.localtime() # 获取本地时间
time.struct_time(tm_year=2021, tm_mon=7, tm_mday=27, tm_hour=16, tm_min=55, tm_sec=18, tm_wday=1, tm_yday=208, tm_isdst=0)
>>> ltime = time.localtime()
>>> ltime.tm_year
2021
>>> ltime.tm_mon
7
>>> ltime.tm_mday
27
>>> print("%s-%s-%s %s:%s:%s" %(ltime.tm_year, ltime.tm_mon, ltime.tm_mday, ltime.tm_hour, ltime.tm_min, ltime.tm_sec)) # 获取本地时间(方便格式化时间显示)
2021-7-27 16:58:17
>>> time.sleep(10) # 程序休眠10s
>>> time.time() # 获取时间戳(1970-7-1 0:0:0 到当前时间的秒数)
1627377088.9805143
>>> time.strftime("%Y-%m-%d %H:%M:%S") # 时间对象格式化显示,转换成字符串
2021-07-27 17:19:30
>>> ss = "2008-08-08 08:08:08" # 将字符串转换为时间对象
>>> time.strptime(ss, "%Y-%m-%d %H:%M:%S")
time.struct_time(tm_year=2008, tm_mon=8, tm_mday=8, tm_hour=8, tm_min=8, tm_sec=8, tm_wday=4, tm_yday=221, tm_isdst=-1)
9、datetime
作用:时间相关(是对time模块的补充)
>>> import datetime
>>> dir(datetime)
[MAXYEAR, MINYEAR, __builtins__, __cached__, __doc__, __file__, __loader__, __name__, __package__, __spec__, date, datetime, datetime_CAPI, sys, time, timedelta, timezone, tzinfo]
>>> from datetime import datetime
>>> dir(datetime)
[__add__, __class__, __delattr__, __dir__, __doc__, __eq__, __format__, __ge__, __getattribute__, __gt__, __hash__, __init__, __init_subclass__, __le__, __lt__, __ne__, __new__, __radd__, __reduce__, __reduce_ex__, __repr__, __rsub__, __setattr__, __sizeof__, __str__, __sub__, __subclasshook__, astimezone, combine, ctime, date, day, dst, fold, fromisocalendar, fromisoformat, fromordinal, fromtimestamp, hour, isocalendar, isoformat, isoweekday, max, microsecond, min, minute, month, now, replace, resolution, second, strftime, strptime, time, timestamp, timetuple, timetz, today, toordinal, tzinfo, tzname, utcfromtimestamp, utcnow, utcoffset, utctimetuple, weekday, year]
>>> datetime.now() # 获取当前时间
datetime.datetime(2021, 7, 27, 17, 32, 28, 13861)
10、calendar
作用:日历相关模块
>>> import calendar
>>> dir(calendar)
[Calendar, EPOCH, FRIDAY, February, htmlCalendar, IllegalMonthError, IllegalWeekdayError, January, LocaleHTMLCalendar, LocaleTextCalendar, MONDAY, SATURDAY, SUNDAY, THURSDAY, TUESDAY, TextCalendar, WEDNESDAY, _EPOCH_ORD, __all__, __builtins__, __cached__, __doc__, __file__, __loader__, __name__, __package__, __spec__, _colwidth, _locale, _localized_day, _localized_month, _monthlen, _nextmonth, _prevmonth, _spacing, c, calendar, datetime, day_abbr, day_name, different_locale, error, firstweekday, format, formatstring, isleap, leapdays, main, mdays, month, month_abbr, month_name, monthcalendar, monthrange, prcal, prmonth, prweek, repeat, setfirstweekday, sys, timegm, week, weekday, weekheader]
11、UUID
作用:获取用不重复的字符串
>>> import uuid
>>> dir(uuid)
[Enum, NAMESPACE_DNS, NAMESPACE_OID, NAMESPACE_URL, NAMESPACE_X500, RESERVED_FUTURE, RESERVED_MICROSOFT, RESERVED_NCS, RFC_4122, SafeUUID, UUID, _AIX, _DARWIN, _GETTERS, _LINUX, _OS_GETTERS, _UuidCreate, _WINDOWS, __author__, __builtins__, __cached__, __doc__, __file__, __loader__, __name__, __package__, __spec__, _arp_getnode, _find_mac, _generate_time_safe, _has_uuid_generate_time_safe, _ifconfig_getnode, _ip_getnode, _ipconfig_getnode, _is_universal, _lanscan_getnode, _last_timestamp, _load_system_functions, _netbios_getnode, _netstat_getnode, _node, _popen, _random_getnode, _unix_getnode, _uuid, _windll_getnode, bytes_, getnode, int_, os, platform, sys, uuid1, uuid3, uuid4, uuid5]
>>> uuid.uuid4() # 获取用不重复的字符串,每次获取都不相同
UUID(c6e232f2-f55c-4918-b0ac-397cd5f5d518)
>>> uuid.uuid4().hex
abe6f101edc448c4b9de6828e709c8e2
>>> uuid.uuid4().hex
e41a9b3e006c45ee9c5c43f3e1e64ba8
>>> uuid.uuid4().hex
4a22a06747a042c6ac536500e907c9a4
>>> uuid.uuid4().hex
7300954d813b40dcace0606d02c531b9
五、IO 流操作
常见的持久化技术:
- 内存 ----> 磁盘
- 数据库
什么是IO流:
IO流指的就是计算机的输入输出操作,常见IO操作,一般说的是内存与磁盘之间的输入输出,IO流操作是一种常见的持久化技术。
1、open 全局函数
open函数的帮助手册
>>> help(open)
Help on built-in function open in module io:
open(file, mode=r, buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)
Open file and return a stream. Raise OSError upon failure.
file is either a text or byte string giving the name (and the path
if the file isnt in the current working directory) of the file to
be opened or an integer file descriptor of the file to be
wrapped. (If a file descriptor is given, it is closed when the
returned I/O object is closed, unless closefd is set to False.)
mode is an optional string that specifies the mode in which the file
is opened. It defaults to r which means open for reading in text
mode. Other common values are w for writing (truncating the file if
it already exists), x for creating and writing to a new file, and
a for appending (which on some Unix systems, means that all writes
append to the end of the file regardless of the current seek position).
In text mode, if encoding is not specified the encoding used is platform
dependent: locale.getpreferredencoding(False) is called to get the
current locale encoding. (For reading and writing raw bytes use binary
mode and leave encoding unspecified.) The available modes are:
========= ===============================================================
Character Meaning
--------- ---------------------------------------------------------------
r open for reading (default)
w open for writing, truncating the file first
x create a new file and open it for writing
a open for writing, appending to the end of the file if it exists
b binary mode
t text mode (default)
+ open a disk file for updating (reading and writing)
U universal newline mode (deprecated)
========= ===============================================================
The default mode is rt (open for reading text). For binary random
access, the mode w+b opens and truncates the file to 0 bytes, while
r+b opens the file without truncation. The x mode implies w and
raises an `FileExistsError` if the file already exists.
Python distinguishes between files opened in binary and text modes,
even when the underlying operating system doesnt. Files opened in
binary mode (appending b to the mode argument) return contents as
bytes objects without any decoding. In text mode (the default, or when
t is appended to the mode argument), the contents of the file are
returned as strings, the bytes having been first decoded using a
platform-dependent encoding or using the specified encoding if given.
U mode is deprecated and will raise an exception in future versions
of Python. It has no effect in Python 3. Use newline to control
universal newlines mode.
buffering is an optional integer used to set the buffering policy.
Pass 0 to switch buffering off (only allowed in binary mode), 1 to select
line buffering (only usable in text mode), and an integer > 1 to indicate
the size of a fixed-size chunk buffer. When no buffering argument is
given, the default buffering policy works as follows:
* Binary files are buffered in fixed-size chunks; the size of the buffer
is chosen using a heuristic trying to determine the underlying devices
"block size" and falling back on `io.DEFAULT_BUFFER_SIZE`.
On many systems, the buffer will typically be 4096 or 8192 bytes long.
* "Interactive" text files (files for which isatty() returns True)
use line buffering. Other text files use the policy described above
for binary files.
encoding is the name of the encoding used to decode or encode the
file. This should only be used in text mode. The default encoding is
platform dependent, but any encoding supported by Python can be
passed. See the codecs module for the list of supported encodings.
errors is an optional string that specifies how encoding errors are to
be handled---this argument should not be used in binary mode. Pass
strict to raise a ValueError exception if there is an encoding error
(the default of None has the same effect), or pass ignore to ignore
errors. (Note that ignoring encoding errors can lead to data loss.)
See the documentation for codecs.register or run help(codecs.Codec)
for a list of the permitted encoding error strings.
newline controls how universal newlines works (it only applies to text
mode). It can be None, , \\n, \\r, and \\r\\n. It works as
follows:
* On input, if newline is None, universal newlines mode is
enabled. Lines in the input can end in \\n, \\r, or \\r\\n, and
these are translated into \\n before being returned to the
caller. If it is , universal newline mode is enabled, but line
endings are returned to the caller untranslated. If it has any of
the other legal values, input lines are only terminated by the given
string, and the line ending is returned to the caller untranslated.
* On output, if newline is None, any \\n characters written are
translated to the system default line separator, os.linesep. If
newline is or \\n, no translation takes place. If newline is any
of the other legal values, any \\n characters written are translated
to the given string.
If closefd is False, the underlying file descriptor will be kept open
when the file is closed. This does not work when a file name is given
and must be True in that case.
A custom opener can be used by passing a callable as *opener*. The
underlying file descriptor for the file object is then obtained by
calling *opener* with (*file*, *flags*). *opener* must return an open
file descriptor (passing os.open as *opener* results in functionality
similar to passing None).
open() returns a file object whose type depends on the mode, and
through which the standard file operations such as reading and writing
are performed. When open() is used to open a file in a text mode (w,
r, wt, rt, etc.), it returns a TextIOWrapper. When used to open
a file in a binary mode, the returned class varies: in read binary
mode, it returns a BufferedReader; in write binary and append binary
modes, it returns a BufferedWriter, and in read/write mode, it returns
a BufferedRandom.
It is also possible to use a string or bytearray as a file for both
reading and writing. For strings StringIO can be used like a file
opened in a text mode, and for bytes a BytesIO can be used like a file
opened in a binary mode.
open 函数的用法
IO操作 open
f = open(file, "r") # f对象就是python IO对象
# read(size=-1) # 读取
# write(data) # 写入到文件
# writelines() # 将多个数据写入
# flush() # 刷新缓存区
# close() # 关闭File对象,注意close自动的调用flush进行最后的文件刷新
2、IO 字符流操作
>>> import os
>>> from os import path
>>> path.abspath(".")
C:\\\\Users\\\\DELL
>>> f = open(wan.txt)
>>> f
<_io.TextIOWrapper name=wan.txt mode=r encoding=cp936>
>>> type(open("wan.txt"))
<class _io.TextIOWrapper>
>>> dir(f)
[_CHUNK_SIZE, __class__, __del__, __delattr__, __dict__, __dir__, __doc__, __enter__, __eq__, __exit__, __format__, __ge__, __getattribute__, __gt__, __hash__, __init__, __init_subclass__, __iter__, __le__, __lt__, __ne__, __new__, __next__, __reduce__, __reduce_ex__, __repr__, __setattr__, __sizeof__, __str__, __subclasshook__, _checkClosed, _checkReadable, _checkSeekable, _checkWritable, _finalizing, buffer, close, closed, detach, encoding, errors, fileno, flush, isatty, line_buffering, mode, name, newlines, read, readable, readline, readlines, reconfigure, seek, seekable, tell, truncate, writable, write, write_through, writelines]
>>> f.read()
hello python
>>> f.read()
>>> f.close()
注意:IO流非常宝贵资源,操作完之后需要关闭IO流。
IO流的使用
>>> f = open("wan.txt") # 读入流
>>> f
<_io.TextIOWrapper name=wan.txt mode=r encoding=cp936>
>>> file = f.read()
>>> file
hello python
>>> f.close()
>>> f = open("wan.txt", mode=w) # 写入流
>>> f
<_io.TextIOWrapper name=wan.txt mode=w encoding=cp936>
>>> f.write("hello world")
11
>>> f.close()
# 查看结果
hello world
>>> f = open("wan.txt", mode=w) # 追加流
>>> f
<_io.TextIOWrapper name=wan.txt mode=w encoding=cp936>
>>> f.write("hello world")
11
>>> f.close()
>>> f = open("wan.txt", mode="a")
>>> f
<_io.TextIOWrapper name=wan.txt mode=a encoding=cp936>
>>> f.write("hello python")
12
>>> f.close()
>>> f = open("wan.txt", mode="a")
>>> f.write("hello c")
7
>>> f.close()
>>> f = open("wan.txt", mode="a")
>>> f.write("hello java")
10
>>> f.close()
# 查看结果
hello worldhello pythonhello chello java
换行操作
>>> f = open("wan.txt", mode="a")
>>> f.write("hello c++")
9
>>> f.close()
>>> f = open("wan.txt", mode="a")
>>> f.write("hello php\\n")
10
>>> f.close()
>>> f = open("wan.txt", mode="a")
>>> f.write("hello go\\n")
9
>>> f.close()
>>> f = open("wan.txt", mode="a")
>>> f.write("hello c#\\n")
9
>>> f.close()
# 查看结果
hello worldhello pythonhello chello java c++ php
go
c#
IO流的分类:
- 按照数据流动(内存而言)
- 输入流
- 输出流
- 按照数据的类型
- 字节流
- 字符流
字符流复制文件
def io_operater(url1, url2):
f1 = open(url1, mode="r")
f2 = open(url2, mode="w")
msg = f1.read()
f2.write(msg)
f1.close()
f2.close()
io_operater("E:\\\\Users\\\\DELL\\\\Desktop\\\\Python Study\\\\a.txt", \\
"E:\\\\Users\\\\DELL\\\\Desktop\\\\Python Study\\\\b.txt")
3、IO 字节流操作
字节流复制文件
f1 = open("a.jfif", mode="rb")
f2 = open("b.jfif", mode="wb")
f2.write(f1.read())
f1.close()
f2.close()
字节流复制文件(限制每次服务数据量)
def copy_file(src, dest):
f1 = open(src, mode="rb")
f2 = open(dest, mode="wb")
# f2.write(f1.read())
# 由于字符流数据流过大,基于性能考虑,我们1M读取一次
while True:
data_volume = f1.read(1024 * 1024)
if data_volume == b"":
print("数据已经读取完成")
break
else:
01 如何学习Python Web开发从入门到实战
Python Web开发从入门到实战
前言:
Python Web是学校所学的课程,我希望在学习的同时通过写笔记的形式来记录我学习以及由学校学习转而自身对此方向感兴趣的一个过程,更多还是让自己在课程结束之后进行一个小的总结来回顾、提高自己。当然也不会缺少我在学习过程中所碰到的一些问题的记录。
《Python Web开发从入门到实战》是作为我学习的参考资料,它可以快速地上手实战,这本书是以一个实际的企业门户网站为例展开,希望通过学习我也可以掌握Python Web的各个开发要点和难点。
下面正式进入学习部分:😄😁😁👩💻👩💻👩💻
Part1 基础知识篇
第一章 Python Web环境搭建
1.1 Python Web的简单介绍
近两年人工智能的火热直接带动了Python这门编程语言的地位,在开源平台Git Hub上,Python也超越了传统的具有垄断性地位的Java。Python所呈现的较快的发展势头,相比其他语言也更拥有绝对的优势。
Python语言是一种面向对象、解释型的程序设计语言,由Guido van Rossum于1989年发明。与传统语言相比,它更为轻巧、语法更接近自然语言。
Python具有三大优势:免费、开源、庞大的第三方库,这三个优势使得Python成为人工智能、网络爬虫、数据分析等领域的首选语言
Python Web在国外发站迅猛,但在国内发展较为缓慢。主要原因在于Python在国内的普及时间还不长,众多的Web开发人员还未及时转移到Python Web上来。
1.2 为什么使用Python Web?
不少人认为Python Web只是众多互联网后端框架的一种,只是单纯用来制作网站的一种工具,功能类似于APP,这种观点是不正确的。首先让我们弄清楚一个概念:
Web = Web application(网络应用) != Website (网站)
即 Web 开发里的 Web 指的是网络应用(Web application),而不仅仅是指网站(Website)。如 果精通 Python Web 开发,那么意味着,Python 的其它领域的核心功能可以直接嵌套进 Python Web 框架里面,可以快速的完成基于互联网的产品应用部署。具体创建什么样的产品完全取 决于你的想法、企业和应用场景。
1.3 Python Web优秀的框架之一: Django
Django具有完整的Web构建方案,其学习文档和参考资料也是非常丰富。
1.4 环境的安装(Python 3、VSCode、Django)
在正式进入学习之前,肯定是不能缺少我们的基础环境。下面我们就要进行基本环境的安装,我们需要装三个部分,分别是Python 3、VSCode、Django.我们需要注意的是安装过程中一定要配置好对应的环境变量
①Python 3 安装:
Python 是一种跨平台语言,因此用 Python 编写的代码可以在 Windows、Linux 和 Mac 上运行,我们下载安装版本 Python 3。
官网下载地址:https://www.python.org/getit/
我安装在D盘下的Programs文件夹中,安装界面要勾选上“Add Python 3.7 to PATH”
测试是否安装成功,只需要打开cmd窗口,并输入python后回车,显示一下画面即成功:
② 安装开发工具VS Code
在 Build 2015 大会上,微软除了发布 Microsoft Edge 浏览器和新的 Windows 10 系 统外,还同时推出了免费跨平台的 Visual Studio Code 编辑器(以下简称 VS Code)。
VS Code 是一款免费开源的现代化轻量级代码编辑器
官网下载地址:https://code.visualstudio.com/
Python Web项目经常使用到的插件
(1)Python:Python 语言的 VS Code 扩展插件,提供了 python 语言的内联、调试、智能感 知、代码导航、重构、单元测试等功能;
(2)Beautify:代码自动对齐插件,可以对 Web 前端 HTML、CSS、JavaScript 的代码进行自 动对齐‘
(3)vscode-icons:图标插件,可以按照文件或者文件夹的不同类型在 VS Code 中以不同的 图标进行显示,方便文件辨识
③ Django安装 注意环境变量的设置,检查没有便手动添加
Django 是众多框架中使用 者最多、框架最全的框架。Django 采用 Python 语言编写,它源自一个在线新闻 Web 站点, 于 2005 年以开源的形式被发布
Django开发Web应用所具有的优势:
(1)Django 是一个由 Python 写成的开源 Web 应用框架,因此继承了 Python 语言具有的简 洁、轻量等特性,拥有丰富的第三方组件,适合快速构建项目;
(2)Django 拥有强大的数据库功能;
(3)自带强大的后台功能;
(4)具有模板系统;
(5)类似热插拔的 App 应用理念
可插拔是指当 Django 项目中某个应用功能不需要了,可 以直接删除,需要的应用功能则可以直接拿来使用,各个应用相对独立,不影响项目的整体 架构,应用的添加和删除操作非常方便
(6)优秀缓存、错误提示等
【本地安装】
在官网下载压缩包如图所示
解压缩到与Python同一目录下,以cmd窗口打开setup.py的文件后输入一下代码:
python setup.py install //安装 python //测试,进入交互界面 import django django.get_version() //查看版本信息,如图为4.0.2的版本
【Terminal安装】
pip install django (django==4.0.2) //pip安装或指定版本 pip install pytz pip install sqlparse //安装相关组件 python //测试,进入交互界面 import django django.get_version() //查看版本信息,如图为4.0.2的版本
1.5 创建一个Django项目并测试
D盘项目下新建一个空文件夹pythonweb1,并打开此文件夹。
django-admin startproject w1 //创建一个名为w1的Django项目 cd w1 //切换到项目w1钟 python manage.py runserver //启动项目来查看是否创建成功,打开terminal给出的网址,如图显示项目创建成功。
Python Web的第一篇学习笔记就到这儿了,持续更新中…💻💻💻
以上是关于我的Python学习之路,从入门到实战的主要内容,如果未能解决你的问题,请参考以下文章
量化资料学习《Python与量化投资从基础到实战》+《量化交易之路用Python做股票量化分析》+《组织与管理研究的实证方法第2版》