Python 脚本练习(笔记)
目录
模糊搜索文件文件自动归类压缩解压zip删除重复文件读取csv并自定义格式wxpy(现在网页微信不能用了,仅学习思路)处理异常
模糊搜索文件
import os
#获取绝对路径
path = '/Users/小侯同学/Camera'
files = os.listdir(path)
for f in files:
if '10' in f and f.endswith('.jpg'):
print('Found if !' + f)
import os
path = '.files'
files = os.listdir(path)
for f in files:
if (not f.endswith('.gif')) and ('project30' in f or 'commercial' in f):
print('Found it' + f)
文件自动归类
import os
import shutil
# 相对路径
path = './problem_files'
# 创建文件夹
os.makedirs(path + '/picture')
os.makedirs(path + '/document')
# 将待处理后缀名存储到相应列表中
picture_suffix = ['jpg', 'png', 'gif']
doc_suffix = ['docx', 'pdf', 'txt']
# 移动并删除
for p in picture_suffix:
cur_path = path + '/' + p
files = os.listdir(cur_path)
for f in files:
shutil.move(cur_path + '/' + f, path + '/picture')
# 删除
os.removedirs(cur_path)
for d in doc_suffix:
cur_path = path + '/' + d
files = os.listdir(cur_path)
for f in files:
shutil.move(cur_path + '/' + f, path + '/document')
os.removedirs(cur_path)
压缩解压zip
import os
import shutil
##解压
#找到文件
def scan_file():
files = os.listdir()
for f in files:
if f.endswith('.zip'):
return f
def unzip_it(f):
folder_name = f.split('.')[0] #.之前所有内容
target_path='/'+folder_name
os.makedirs(target_path)
shutil.unpack_archive(f,target_path)
def delete(f):
os.remove(f)
while True:
zip_file = scan_file()
if zip_file:
unzip_it(zip_file)
delete(zip_file)
##压缩
import os
import shutil
import time
#待压缩
doc_path = './document'
#输出路径
output_path = './output'
zip_count = 0
while True:
files = os.listdir(doc_path)
files_count = len(files)
if files_count >= 10:
zip_count = zip_count+1
zip_name = output_path+'/'+'archive'+str(zip_count)
shutil.make_archive(zip_name,'zip',doc_path)
for f in files:
os.remove(doc_path+'/'+f)
time.sleep(1)
删除重复文件
import filecmp
import os
path = './problem_files'
# 已有文件夹
docs = ['doc1', 'doc2']
#全部放在一个文件夹里
def get_all_files(path, dirs):
all_files = []
for d in dirs:
cur_path = path + '/' + d
files = os.listdir(cur_path)
for f in files:
all_files.append(cur_path + '/' + f)
return all_files
def cmp_files(a,b):
if filecmp.cmp(a,b):
os.remove(b)
print("已删除""+b)
#调用函数
all_files = get_all_files(path,docs)
for a in all_files:
for b in all_files:
if a!=b and os.path.exists(a) and os.path.exists(b):
cmp_files(a,b)
读取csv并自定义格式
import csv
def read_info():
f = open('./sample.csv', 'r')
reader = csv.DictReader(f)
return [info for info in reader]
def make_msg(raw_info):
t = '{n}-请于{t}参加{s}在{a}'
return [t.format(n=info['姓名'],
t=info['时间'],
s=info['课程'],
a=info['地址']) for info in raw_info]
raw_info = read_info()
msg = make_msg(raw_info)
print(msg)
wxpy(现在网页微信不能用了,仅学习思路)
#从csv文档匹配相应昵称发送对应信息
import csv
import time
from wxpy import *
FRIENDS = ['Alice', 'Bob', 'Jack']
CSV_PATH = './sample.csv'
def read_csv(path):
f = open(path, 'r', encoding='utf-8')
reader = csv.DictReader(f)
# print([info for info in reader])
return [info for info in reader]
def get_msg(infos, name):
template = "{name},请在{time}来{event}在{location},{note}"
for info in infos:
if info['微信昵称'] == name:
msg = template.format(name=info['微信昵称'],
time=info['时间'],
event=info['事件'],
location=info['地址']
)
return msg
return None # 如果没有找到
def send_to_friends(infos, friends):
bot = Bot()
for friend in friends:
friend_search = bot.friends().search(friend)
if (len(friend_search) == 1):
msg = get_msg(infos,friends)
if msg:
friend_search[0].send(msg)
else:
print("发送失败csv中没有"+friend)
else:
print("发送失败,无好友"+friend)
time.sleep(3)
send_to_friends(read_csv(CSV_PATH),FRIENDS)
# 自动处理加群,加好友
import time
from wxpy import *
bot = Bot()
def listen(pwd):
time.sleep(3)
return [msg for msg in bot.messages if msg.text == pwd]
def add(users, group):
try:
group.add_numbers(users, use_invitation=True)
return group
except ResponseError:
return None
def get_newfriend(say):
time.sleep(3)
return [msg for msg in bot.messages if msg.text == say]
group = bot.groups().search('test group 1')[0]
while True:
new_friend = get_newfriend('Make friend')
if new_friend:
for msg in new_friend:
new_user = msg.card
bot.accept_friend(new_user)
new_user.send('Hi')
bot.messages.remove(msg)
time.sleep(3)
selected = listen('Pull me in')
if selected:
for msg in selected:
this_user = msg.sender
add(this_user,group)
bot.messages.remove(msg)
# 日志统计 //先不考虑改名字
import time
from wxpy import *
def find_group(bot, name):
try:
result = bot.groups().search(name)
if len(result) == 1:
return result[0]
else:
print("查找失败没有找到对应目标")
return None
except ResponseError as e:
print(e.err_code, e.err_msg)
def get_members(group):
try:
return group.numbers
except ResponseError as e:
print(e.err_code, e.err_msg)
def parse_members(cur_members, last_members):
# 退群
quit_list = [list.name for last in last_members if last not in cur_members]
# 进群
new_list = [cur.name for cur in cur_members if cur not in cur_members]
return "退群".join(quit_list) + "n" + "进群".join(new_list)
def send_msg(bot, my_name, text):
try:
myself = bot.friends().search(my_name)[0]
myself.send(text)
except ResponseError as e:
print(e.err_code, e.err_msg)
def main(my_name, group_name):
bot = Bot()
group = find_group(bot, group_name)
last_members = get_members(group)
while True:
time.sleep(3600)
cur_members = get_members(group)
msg = parse_members(cur_members,last_members)
send_msg(bot,my_name,msg)
main("微信名","群聊名")
处理异常
while True:
print('Give number')
num = input()
try:
print(100/int(num))
except ValueError:
print("输入错误请输入数字")
except ZeroDivisionError:
print("请输入非零")