目录
一、 MicroPython
1.1 所用开发板
1.2 Th开发环境、ESP32-python固件、官方文档
1.3 代码
1.3.0 点灯
1.3.1 定时器
1.3.2 PWM
1.3.2 PWM 控制舵机
1.3.3 TCP\UDP通信
1.3.4 LCD1602
1.3.5 数码管
1.3.6 SSD1306
1.3.7 DS18B20
1.3.8 WS2812b
1.3.9 74HC595数码管
1.3.10 MAX7219数码管
1.3.11 IIC-OLED
1.3.12 GY-30光照传感器
1.3.13 AHT10
1.3.13 DHT11
1.3.14 HCSR04
1.3.15 获取网络时间
1.3.16 获取心知天气
1.3.17 I2S播放WAV
1.4 参考资料
二 、 Pyhon
1.1 语法
1.1.0
1.1.1 语法糖
1.2 例子
1.2.0 Python爬取Bing图片
1.2.1 批量修改文件名
Thonny, Python IDE for beginners
MicroPython - Python for microcontrollers
Overview — MicroPython latest documentation
micropython: micropython官方库 https://github.com/micropython/micropython.git
GitHub - micropython/micropython-lib: Core Python libraries ported to MicroPython
//点灯
from machine import Pin //导入GIPO库
Pin2 = Pin(2,Pin.OUT) //设置pin2口
pin2.on()
pin2.off()
//读取电平设置电平
pin2.value()//读
pin2.value(1)//设置
//Python库的函数粗延时
from machine import Pin
import time
pin2 = Pin(2,Pin.OUT)
while True:
pin2.on()
time.sleep_ms(50)
pin2.off()
time.sleep_ms(50)
#def 定义
#period 时期
#PERIODIC 周期模式
#callback 回调
#lambda 入/闭包就是匿名函数,没有名字的函数,属于函数式编程概念
from machine import Pin,Timer
led = Pin(2,Pin.OUT)
def led_get(Tim):
print(led.value())
led.on()
Tim = Timer(0)
Tim.init(period = 1000 ,mode = Timer.PERIODIC,callback = led_get)
Tim = Timer(1)
Tim.init(period = 2000 ,mode = Timer.PERIODIC,callback = lambda t:led.off())
from machine import Pin,PWM
import time
pwm = PWM(Pin(2))
pwm.freq(1000)
def pwm_set():
while True:
for i in range(0,1024,1):
pwm.duty(i)
time.sleep_ms(1)
for i in range(1023,0,-1):
pwm.duty(i)
time.sleep_ms(1)
pwm_set()
from machine import Pin,PWM
import time
motor = PWM(Pin(2),freq = 50 ,duty = 0)
def motor_test():
while True:
for i in range(0,181,1):
motor.duty(int((i/90+0.5)/20*1023))
time.sleep_ms(1)
for i in range(180,-1,-1):
motor.duty(int((i/90+0.5)/20*1023))
time.sleep_ms(1)
motor_test()
TCP
import networK //导入库
wlan = network.WLAN(network.STA_IF) //创建waln对象,STA_IF从机模式 ESP32用的是2.4G
wlan.active(True) //是否启动WIFI
wlan.scan() //扫描附近WiFi
wlan.isconnected() //是否连接过网络
wlan.connect('HIKVISION_6CA780','yhnokn..123') //连接WiFi
wlan.config('mac') //查看ESP32设备MAC
wlan.ifconfig() //查看路由器给设备分配的IP
from socket import * //导入库
tcp_socket = socket(AF_INET,SOCK_STREAM)
serve_ip = "192.168.0.196"
serve_port = 8080
tcp_socket.connect((serve_ip,serve_port)) //连接本地的网络调试助手服务器,参数是元组形式
send_data = "this is a message" //发送数据
tcp_socket.send(send_data.encode("utf-8"))
from_serve_msg = tcp_socket.recv(1024) //接收数据
print(from_serve_msg.decode("utf-8"))
UDP
from socket import *
udp_socket = socket(AF_INET,SOCK_DGRAM)
dest_addr = ("192.168.0.196",8080)
send_data = "this is a message"
udp_socket.sendto(send_data.encode('utf-8'),dest_addr)
UDP 联网点亮LED
from machine import Pin
from socket import *
import network
import time
#网络配置
def do_connect():
wlan = network.WLAN(network.STA_IF)#创建WLAN对象
wlan.active(True)#激活WLAN
if not wlan.isconnected():
print('connecting to network...')
wlan.connect('HIKVISION_6CA780','yhnokn..123')
while not wlan.isconnected():
pass
print('network config',wlan.ifconfig())
#创建网络连接
def create_network_socket():
udp_socket = socket(AF_INET,SOCK_DGRAM)#创建UDP套接字
udp_socket.bind(("192.168.0.188",8080))#绑定端口
return udp_socket
#接收数据函数
def udp_RXT_data():
do_connect()
udp_socket = create_network_socket()
led = Pin(2,Pin.OUT)
while True:
#接收的数据 #发送者地址 #接收字节的长度
recv_data,sendr_info = udp_socket.recvfrom(1024)
#解码接收到的数据以便打印出中文
recv_data_srt = recv_data.decode("utf8")
print("数据内容:{} 数据地址:{}".format(recv_data_srt,sendr_info))
if recv_data_srt == "开灯":
led.value(1)
elif recv_data_srt == "关灯":
led.value(0)
def main():
udp_RXT_data()
if __name__ == "__main__":
main()
TCP 联网点亮LED
from machine import Pin
from socket import *
import network
import time
#网络配置
def do_connect():
wlan = network.WLAN(network.STA_IF)#创建WLAN对象
wlan.active(True)#激活WLAN
if not wlan.isconnected():
print('connecting to network...')
wlan.connect('HIKVISION_6CA780','yhnokn..123')
while not wlan.isconnected():
pass
print('network config',wlan.ifconfig())
#创建网络连接
def create_network_socket():
tcp_socket = socket(AF_INET,SOCK_STREAM)#创建套接字
serve_ip = "192.168.0.196"#需要连接服务器地址
serve_port = 8080 #需要连接的端口
tcp_socket.connect((serve_ip,serve_port))
return tcp_socket
#接收数据函数
def tcp_RXT_data():
do_connect()
tcp_socket = create_network_socket()
led = Pin(2,Pin.OUT)
while True:
#接收的数据
recv_data = (tcp_socket.recv(1024).decode("utf-8"))
print("{}".format(recv_data))
if recv_data == "开灯":
led.value(1)
elif recv_data == "关灯":
led.value(0)
def main():
tcp_RXT_data()
if __name__ == "__main__":
main()
『if __name__ == "__main__"』到底啥意思❓
导入所所需要的库: lcd_api.py 和 machine_i2c_lcd.py
下载地址 GitHub - dhylands/python_lcd: Python based library for talking to character based LCDs.
from machine import SoftI2C,Pin
from machine_i2c_lcd import I2cLcd
import time
lcd_addr = 0x27
I2C = SoftI2C(scl = Pin(16),sda = Pin(4),freq = 100000)
lcd = I2cLcd(I2C,lcd_addr,2,16)
def main():
while True:
for i in range(0,10):
lcd.clear()
lcd.putchar("{}".format(i))
time.sleep_ms(1000)
if __name__ == "__main__":
main()
(列表、字典知识点)
from machine import Pin
import time
gnd = Pin(0,Pin.OUT)
a = Pin(12,Pin.OUT)
b = Pin(14,Pin.OUT)
c = Pin(27,Pin.OUT)
d = Pin(26,Pin.OUT)
e = Pin(25,Pin.OUT)
f = Pin(33,Pin.OUT)
g = Pin(32,Pin.OUT)
dp = Pin(2,Pin.OUT)
#列表(数组)
smg_pin = [a,b,c,d,e,f,g,dp]
#字典
smg_code = {
0:"11111100",#键:值 (效果一样)"11111100":0
1:"01100000",
2:"11011000",
3:"11110010",
4:"01100110",
5:"11100110",
6:"10111110",
7:"11100000",
8:"11111110",
9:"11110110",
}
def smg_disply(num):
gnd.value(0)
if smg_code.get(num): #判断传入值是否在字典中
i = 0;
for count in smg_code.get(num):#在字典中则将键值按位赋值给count
if count == "1": #字符型的比较
smg_pin[i].value(1)
else:
smg_pin[i].value(0)
i+=1;
def main():
smg_disply(0)
time.sleep(1)
while True:
pass
if __name__ == "__main__":
main()
SSD1306官方驱动库:SSD1306
SPI方式驱动(用到的OLED为带字库的接线方式有所不同)用到CLK、MOSI、DC、CS1
from machine import Pin,SoftSPI
from ssd1306 import SSD1306_SPI
import time
dc = Pin(2,Pin.OUT)
res = Pin(15,Pin.OUT)
cs = Pin(4,Pin.OUT)
spi = SoftSPI(baudrate=100000, polarity=1, phase=0, sck=Pin(18), mosi=Pin(23), miso=Pin(19))
oled = SSD1306_SPI(128,64,spi,dc,res,cs)
def main():
oled.text("littleone",24,28,1)
while True:
for i in range(100):
oled.fill(0)
oled.text("littleone:%d"%i,24,28,1)
oled.invert(i)
oled.rotate(i)
oled.contrast(i)
oled.show()
time.sleep(1)
if __name__ == "__main__":
main()
(一线通信接口)
from machine import Pin
import onewire,ds18x20,time
#创建单总线对象
ONEWIRE = onewire.OneWire(Pin(2))
#创建ds18b20对象
DS18B20 = ds18x20.DS18X20(ONEWIRE)
def dis18b20_read_Temp():
roms =DS18B20.scan() #扫描ds18b20地址
DS18B20.convert_temp() #开始温度转换
time.sleep(1)#12位精度延迟750ms这里延时1s
for rom in roms:#把读取到的器件地址循环写入
temp = DS18B20.read_temp(rom)#读取温度写入器件地址
return temp #将温度值返回
def main():
dis18b20_read_Temp()
while True:
print("temp = %.2f ℃"%dis18b20_read_Temp())
if __name__ == "__main__":
main()
python格式化输出
2^24 = 16,777,216
ws2812教程
from machine import Pin
import neopixel,time
pin = Pin(2,Pin.OUT)
#1:引脚 2:灯珠数 3:颜色格式(3为RGB) 4:频率 0=400K 1=800K
np = neopixel.NeoPixel(pin,n=12,bpp=3,timing=3)
def main():
while True:
for i in range (0,12,1):
np[i] = (24,89,i*8)
np.write()
time.sleep_ms(50)
np.fill((0,0,0))
np.write()
if __name__ == "__main__":
main()
from machine import Pin
import time
ds = Pin(15,Pin.OUT) #DIO数据
RCLK = Pin(0,Pin.OUT) #存储寄存器时钟
SCLK = Pin(2,Pin.OUT) #移位寄存器时钟
def ch595_write_Byte(duan,wei):#段选,位选
for i in range(8):
if duan & 0x80: #0x80=1000 0000
ds.value(1)
else:
ds.value(0)
SCLK.value(0)
SCLK.value(1)
duan <<= 1
for i in range(8):
if wei & 0x80: #0x80=1000 0000
ds.value(1)
else:
ds.value(0)
SCLK.value(0)
SCLK.value(1)
wei <<= 1
RCLK.value(0)
RCLK.value(1)
def ch595_dispy_numberr(num,show_point):
#0-9 共阴 我所用的是共阳所以把每一个数字按位取反 ~0x00为清屏不显示
number = [~0x3f,~0x06,~0x5b,~0x4f,~0x66,~0x6d,~0x7d,~0x07,~0x7f,~0x6f,~0x00]
point = [0x1,0x1<<1,0x1<<2,0x1<<3,0x1<<4,0x1<<5,0x1<<6,0x1<<7]
ch595_write_Byte(number[num],point[show_point])
def main():
while True:
for i in range (8):
ch595_dispy_numberr(i,i)
time.sleep_ms(100)
ch595_dispy_numberr(10,i)
if __name__ == "__main__":
main()
from machine import Pin,SPI
import time
clk = Pin(14,Pin.OUT)
cs = Pin(12,Pin.OUT)
dio = Pin(13,Pin.OUT)
#自己写
"""
def MAX7219_Write(addr,data):
cs.value(0)
for i in range (8):
clk.value(0)
dio.value(1 if((addr<
点阵管
max7219.py
from machine import Pin,SPI
import Max7219,time
cs = Pin(12,Pin.OUT)
spi = SPI(1,1000000,sck=Pin(14),mosi=Pin(13),miso=Pin(19))
MAX = Max7219.Matrix8x8(spi,cs,1)
MAX.init()
def main():
MAX.brightness(7)
MAX.fill(0)
while True:
for i in range(9):
MAX.rect(8-i,8-i,i,i,1)
MAX.show()
time.sleep_ms(50)
MAX.fill(0)
if __name__ == "__main__":
main()
1、Soft/Hard-IIC
from machine import SoftI2C,Pin,I2C
from ssd1306 import SSD1306_I2C
import time
class chinese:
chinese = [
# 晓(0) 小(1) 謏(2)
0x00,0xFC,0x84,0x84,0xFC,0x00,0x88,0x88,0x4F,0x58,0x24,0x54,0x84,0xE4,0x00,0x00,
0x00,0x3F,0x10,0x10,0x3F,0x80,0x42,0x32,0x0E,0x02,0x02,0x3E,0x42,0x42,0x72,0x00,
0x00,0x00,0x00,0xE0,0x00,0x00,0x00,0xFF,0x00,0x00,0x00,0x20,0x40,0x80,0x00,0x00,
0x08,0x04,0x03,0x00,0x00,0x40,0x80,0x7F,0x00,0x00,0x00,0x00,0x00,0x01,0x0E,0x00,
0x08,0xA8,0xA9,0xAE,0xA8,0xA8,0x00,0xFE,0x91,0x80,0xFF,0x80,0x92,0xFE,0x00,0x00,
0x00,0x7E,0x22,0x22,0x22,0x7E,0x80,0x82,0x46,0x2A,0x13,0x2A,0x46,0x82,0x80,0x00,
]
i2c = SoftI2C(scl = Pin(0),sda = Pin(2),freq = 100000)#软件IIC
I2C = I2C(0,scl = Pin(22),sda =Pin(21),freq = 400000)#硬件IIC
addr = 0x3c
oled = SSD1306_I2C(128,64,I2C,addr)
#显示中文
def ByteOpera(num,dat):
byte = [0x01,0x02,0x04,0x8,0x10,0x20,0x40,0x80]
if dat&byte[num]:
return 1
else:
return 0
def LcdShowCh_16x16(n,x_axis,y_axis):
for i in range(2):
for a in range(16):
for b in range(8):
if(ByteOpera(b,chinese.chinese[n*32+i*16+a])):
oled.pixel(x_axis+a,y_axis+i*8+b,1)
else:
oled.pixel(x_axis+a,y_axis+i*8+b,0)
def main():
oled.fill(0)
for i in range (100):
oled.text("littleone:%d"%i,24,28,1)
LcdShowCh_16x16(0,16,0)
LcdShowCh_16x16(1,2*16,0)
LcdShowCh_16x16(2,3*16,0)
# oled.text("little one",24,28)
# oled.text("{}".format(i),110,28)
oled.show()
time.sleep_ms(50);
oled.fill(0)
while True:
pass
if __name__ == "__main__":
main()
from machine import Pin,I2C
from ssd1306 import SSD1306_I2C
import time
i2c = I2C(0,scl = Pin(22),sda = Pin(21),freq =4_00_000)
gy20_addr = int(i2c.scan()[0])
oled_addr = int(i2c.scan()[1])
oled = SSD1306_I2C(128,64,i2c,oled_addr)
# print(hex(i2c.scan()[0]),hex(i2c.scan()[1]))
def Gy_30_Init():
i2c.writeto(gy20_addr,b'\x01')#通电运行
i2c.writeto(gy20_addr,b'\x07')#复位
i2c.writeto(gy20_addr,b'\x10')#高分辨率连续读取 1lx(1流明分辨率) 120ms(测量间隔)
def Gy_30_Show():
gy = i2c.readfrom(gy20_addr,2)#读两个字节16位对应GY30的分辨率
gy30 = float(gy[0] << 8 | gy[1])/1.2#对读回的两个列表项进行合并
time.sleep_ms(200)
return gy30
def main():
Gy_30_Init()
oled.contrast(255)
while True:
oled.fill(0)
oled.text("gy-30 = %.2fLx"%Gy_30_Show(),0,28)
oled.show()
print("%.2fLx"%Gy_30_Show())
if __name__ == "__main__":
main()
库下载链接
import time
from machine import Pin, I2C
import ahtx0
I2C = I2C(0,scl = Pin(22),sda =Pin(21),freq = 400000)#硬件IIC
addr = int(I2C.scan()[0])
sensor = ahtx0.AHT10(I2C,addr)
# Create the sensor object using I2C
# sensor = ahtx0.AHT10(I2C)
while True:
print("\nTemperature: %0.2f C" % sensor.temperature)
print("Humidity: %0.2f %%" % sensor.relative_humidity)
time.sleep_ms(500)
from machine import Pin
import dht
import time
def DHT11():
dht11 = dht.DHT11(Pin(4))
dht11.measure()
print("temp:%.1f"% dht11.temperature())
print("hum:%.1f"% dht11.humidity())
print("\n")
def main():
while True:
DHT11()
time.sleep_ms(10)
if __name__ == "__main__":
main()
编写ntpTime库
from machine import Pin,I2C,RTC
from ssd1306 import SSD1306_I2C
import ntptime,time,network
I2C = I2C(0,scl = Pin(22),sda =Pin(21),freq = 400000)#硬件IIC
addr = 0x3c
oled = SSD1306_I2C(128,64,I2C,addr)
def do_connect():
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
if not wlan.isconnected():
oled.text("connect net...",0,0,1)
oled.show()
wlan.connect('HIKVISION_6CA780','yhnokn..123')
while not wlan.isconnected():
pass
oled.fill(0)
oled.text("connect succeed",0,0,1)
oled.text("ip:%s"%wlan.ifconfig()[0],0,16,1)
oled.text("MSK:%s"%wlan.ifconfig()[1],0,32,1)
oled.text("GW:%s"%wlan.ifconfig()[2],0,48,1)
oled.text("DNS:%s"%wlan.ifconfig()[3],0,64,1)
oled.show()
print('network config:', wlan.ifconfig())
def syne_ntp():
week = ['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday']
rtc = RTC()
ntptime.NTP_DELTA = 3155644800
ntptime.host = "ntp.aliyun.com"
#ntptime.host = "pool.ntp.org"
#time.sleep(1)
oled.fill(0)
try: #异常处理模块
rtc.datetime() #获取本地时间
ntptime.settime() #同步本地时间
oled.text("succeed",0,0,1)
except : #出现异常处理
oled.text("erro ",0,0,1)
times = rtc.datetime()
oled.text("%d-%.2d-%.2d"%(times[0],times[1],times[2]),0,16,1)
oled.text("%.2d-%.2d-%.2d"%(times[4],times[5],times[6]),0,32,1)
oled.text("%s"%(week[times[3]]),0,48,1)
oled.show()
#time.sleep(1)
def main():
do_connect()
while True:
syne_ntp()
if __name__ == "__main__":
main()
main中调用
from ntpTime import do_connect,syne_ntp
import time
def main():
do_connect()
time.sleep(1)
while True:
syne_ntp()
if __name__ == "__main__":
main()
①:注册心知天气获取秘钥
②:导入urequests库 库地址
③:心知的接口免费用户每分钟限制获取20次信息超过就或获取失败所以要加合适的延迟时间
import ntptime,time,network,urequests
import ujson
def get_weather():
get = urequests.get("https://api.seniverse.com/v3/weather/now.json?key=S0uI5uodKzB8Ytdqk&location=fujianfuzhou&language=zh-Hans&unit=c")
decode = ujson.loads(get.text)
Cit_Name = decode["results"][0]["location"]["name"]
Cit_weather = decode["results"][0]["now"]["text"]
Cit_Temp = decode["results"][0]["now"]["temperature"]
#最近一次更新的时间
Cit_time = decode["results"][0]["last_update"]
print(Cit_Name,Cit_weather,Cit_Temp,Cit_time)
def main():
while True:
get_weather()
time.sleep(20)
if __name__ == "__main__":
main()
decode = ujson.loads(get.text) 的解释
Cit_Name = decode["results"][0]["location"]["name"] 的理解
decode = ujson.loads(get.text) 是将原本的Response类转换成dict字典
数据原本是这样的
{"results":[{"location":{"id":"WSSU6EXX52RE","name":"福州","country":"CN","path":"福州,福州,福建,中国","timezone":"Asia/Shanghai","timezone_offset":"+08:00"},"now":{"text":"多云","code":"4","temperature":"27"},"last_update":"2023-05-31T21:52:49+08:00"}]}
转化完了就是一个字典嵌套一个列表(这个列表只有一个元素(对应[0])这个元素是一个嵌套了字典的字典)列表里面有嵌套字典的结构
["results"][0]["location"]["name"] 就是说获取字典中"results"对应的列表中的第一个元素中字典"location"中的字典"name"对应的内容
使用Micropython开发ESP32开发板之通过MAX98357 I2S音频模块播放音乐_魔都飘雪的博客-CSDN博客
本地文件的读写操作只能打开下载到板子中的文件。
Python 教程
MicroPython Esp32物联网微控制器开发
(66条消息) 1.2 ESP32-MicroPython基础操作_micropython查看内存大小_向往生的博客-CSDN博客
快速上手ESP32 — 使用MicroPython编程
让程序在ESP32上电时自动运行
【Python】input()函数用法小结_python input_Darknight: :的博客-CSDN博客
Python中a和a[:]有什么区别?
剑指offer--二进制中1的个数
Python 二进制中1的个数 &0xffffffff是什么意思
C语言,\t的用法-CSDN博客
Python format 格式化函数
在 python 中,类型属于对象,对象有不同类型的区分,变量是没有类型的:
eg:
a=[1,2,3] a="Runoob"
以上代码中, [1,2,3] 是 List 类型, "Runoob" 是 String 类型,而变量 a 是没有类型,她仅仅是一个对象的引用(一个指针),可以是指向 List 类型对象,也可以是指向 String 类型对象。
可更改(mutable)与不可更改(immutable)对象
在 python 中,strings, tuples, 和 numbers 是不可更改的对象,而 list,dict 等则是可以修改的对象。
不可变类型:变量赋值 a=5 后再赋值 a=10,这里实际是新生成一个 int 值对象 10,再让 a 指向它,而 5 被丢弃,不是改变 a 的值,相当于新生成了 a。
可变类型:变量赋值 la=[1,2,3,4] 后再赋值 la[2]=5 则是将 list la 的第三个元素值更改,本身la没有动,只是其内部的一部分值被修改了。
python 函数的参数传递:
不可变类型:类似 C++ 的值传递,如整数、字符串、元组。如 fun(a),传递的只是 a 的值,没有影响 a 对象本身。如果在 fun(a) 内部修改 a 的值,则是新生成一个 a 的对象。
可变类型:类似 C++ 的引用传递,如 列表,字典。如 fun(la),则是将 la 真正的传过去,修改后 fun 外部的 la 也会受影响
python 中一切都是对象,严格意义我们不能说值传递还是引用传递,我们应该说传不可变对象和传可变对象。
匿名函数
Python 使用 lambda 来创建匿名函数。
所谓匿名,意即不再使用 def 语句这样标准的形式定义一个函数。
lambda 只是一个表达式,函数体比 def 简单很多。
lambda 的主体是一个表达式,而不是一个代码块。仅仅能在 lambda 表达式中封装有限的逻辑进去。
lambda 函数拥有自己的命名空间,且不能访问自己参数列表之外或全局命名空间里的参数。
虽然 lambda 函数看起来只能写一行,却不等同于 C 或 C++ 的内联函数,后者的目的是调用小函数时不占用栈内存从而增加运行效率。
语法糖是编程中的某些特殊写法
①:交换量变量的值
a=1; b=2; a,b = b,a(实现交换)
②:判断变量是否落在某个范围内
if 90<=a<=100 print("优秀") 判断啊是否在90-100的范围内
③:快速构造字符串
print('-'*20) 打印出20个-
④:列表拼接
a = [1,2,3] b = [4,5,6] c= a+b
⑤:列表切片
a = [1,2,3,4,5,6,7,8,9] b = a[3:-2] = [4,5,6,7]
⑥:打包与解包
a = (1,2,3) x,y,z = a python会把a解包然后按左边变量的顺序分别赋值给x,y,z
b = (x,y,z) 把xyz的值打包给b
⑦:with语句
正常读取文件分三步
打开文件 f = open('test.txt','r') 读取文件 data = f.read( ) 关闭文件 f.colse() 最后一步关闭文件相当于‘擦屁股’的操作如果不小心忘了或者忽略可能会导致很多麻烦,pyhton用with语句很好的解决了这个问题
用with 没有用关闭文件的语句,但是他能够自动的关闭打开的文件对象自动处理异常
with oprn('test.txt','r') as f:
data = f.read()
⑧:列表推导式
eg:给列表中的元素每个加233
普通的做法:a = [1,2,3] b[] for e in a: b.append(e+233)
推导式: a = [1,2,3] b = [e+233 for e in a]
⑨:数字分割符
a = 10_0000_0000
引例:(6条消息) Python3爬取Bing每日图片,并设置为电脑桌面_python爬取bing每日一图保存_非常的硬朗的博客-CSDN博客
(6条消息) Python实用案例,Python脚本,Python实现每日更换“必应图片”为“桌面壁纸”_千寻编程的博客-CSDN博客
安装各种库的方法:(6条消息) python中import requests报错:No module named ‘requests’_Nancy-sn的博客-CSDN博客
(6条消息) Python3安装Pillow与PIL的方法_pillow资源-CSDN文库
(6条消息) 关于文件路径中/ \ // \\的使用以及绝对相对路径的问题_路径\\_csdndg的博客-CSDN博客
用到的是 os 模块中的 listdir 方法和 rename 方法
import os
path = "c:\\Users\\Heone\\Desktop\\python\\TEST\\"
fileList = os.listdir(path)
n = 0
for i in fileList:
old = path+ os.sep + fileList[n] # os.sep添加系统分隔符
new = path+ os.sep + 'B' + str(n+1) +'.txt'
os.rename(old,new)
n +=1