文本操作,实现边输入边输出
#实现边输入边输出 需要去Windows 找到该记事本文件,修改其内容并保存才可以真正的做到 import os f_read = open(r"..\day6\四大喜事.txt",mode = "r",encoding="utf-8") print(f_read.read()) while True: time_before = os.stat(r'..\day6\四大喜事.txt').st_mtime if os.stat(r'..\day6\四大喜事.txt').st_mtime != time_before: f_read = open(r"..\day6\四大喜事.txt", mode="r", encoding="utf-8") print(f_read.read()) f_read.close()
冒泡排序:
爬一个小网站的内容
import requests def get_url(): url = "http://www.xiaohuar.com/" def get(): ret = requests.get(url) #获取相应码 def url_(): text = ret.text #获取源码文件 return text return url_ return get text = get_url()()() print(text)
二分查找
def find_second(data_list,val): ''' :param data_list: 顺序储存结构 :param val: 需要查找的值 :return: 存在返回该值的索引,不存在返回None ''' left = 0 right = len(data_list) - 1 while right >= left: middle = (right + left) // 2 if val > data_list[middle]: left = middle +1 elif val < data_list[middle]: right = middle -1 else: return middle return
Python 的元组排序:
li = [(1,1,1),(1,0,1),(0,0,0),(1,1,0),(0,0,1)] """ F F F 3 F F T 5 T F T 2 T T F 4 T T T 1 """ li.sort() # print(sorted(li)) #结果:[(0, 0, 0), (0, 0, 1), (1, 0, 1), (1, 1, 0), (1, 1, 1)] print(li) #结果:[(0, 0, 0), (0, 0, 1), (1, 0, 1), (1, 1, 0), (1, 1, 1)]
接受实际报错信息
try: print(1/0) except ZeroDivisionError: s = traceback.format_exc() #实际报错信息 s_index = s.index(':',1) print(type(s)) print(s[s_index+1:].strip())
小帕爬虫读取页面全部信息
import requests # ret = requests.get("http://www.xiaohuar.com/") # print(ret.text) def get_url(): url = "http://www.xiaohuar.com/" def get(): ret = requests.get(url) def url_(): text = ret.text return text return url_ return get text = get_url()()() print(text)
模拟进度条
import sys import time def progress(percent,width=50): if percent >= 1: percent=1 # show_str = ('%%-%ds' % width) % (int(width*percent)*'?') print('\r%s%d%%' %(int(width*percent)*'?', int(100*percent)), end='') #=========应用========== data_size=205000 recv_size=0 while recv_size < data_size: time.sleep(0.1) #模拟数据的传输延迟 recv_size+=1024 #每次收1024 percent=recv_size/data_size #接收的比例 progress(percent,width=70) #进度条的宽度70
展示文件夹内容
#打开文件夹 import os file_path = "d:\" def readFile(file_path , n): #n 控制循环深度 it = os.listdir(file_path) #查看文件夹中的文件 for em in it: #遍历文件 #if os.path.isdir(em): #判断是否为文件夹 if os.path.isdir(os.path.join(file_path, em)) print('\t'*n,em) #打印文件夹 #readFile(em) #此时找不到,因为只是文件名,找的是相对位置。 readFile(os.path.join(file_path, em ) , n+1) #如果是,继续调用本方法 else: print('\t'*n,em) #打印文件 readFile(file_path , 0)