以下代码都是在工作中经常遇到,然而死记硬背下来是不可能的,每次都现查也太麻烦了;因此在这里进行整理,以便以后无数次的使用(长期更新)
获取当前可读时间
1 2
| import time time.strftime("%Y-%m-%d_%H-%M-%S",time.localtime())
|
在输出的excel中插入超链接
1
| =HYPERLINK("https://3g.k.sohu.com/t/n685055087","显示")
|
读写json文件
1 2 3 4 5 6
| with open(path, "w", encoding="utf-8") as f: json.dump(resdict, f, ensure_ascii=False, indent=4)
with open("file.json", encoding="utf-8") as f: resdict = json.load(f)
|
使用pandas读写excel的多个sheet
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| import pandas as pd
writer = pd.ExcelWriter('/path/to/XXX.xlsx') df1.to_excel(writer, "sheet1") df2.to_excel(writer, "sheet2") df3.to_excel(writer, "sheet3") writer.save() writer.close()
df = pd.read_excel("../path/to/XXX.xlsx", sheet_name="sheet1")
dic = {"key1": list1, "key2": list2} DataFrame(dic).to_excel("a.xlsx")
lst = [[1,2,3],["a", "b", "c"]] DataFrame(lst, columns=["数字", "字母"]).to_excel("a.xlsx")
|
获取文件相对路径
1 2
| import os getModulePath = lambda p: os.path.join(os.path.dirname(__file__), p)
|
python操作MySQL数据库
参考资料:点我
一个不用写SQL语句,只需要填参数的工具类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
| import pymysql
class Database(): def __init__(self, **config): try: self.__conn = pymysql.connect(**config) self.__cursor = self.__conn.cursor() except Exception as e: print("数据库连接失败:\n", e)
def select_one(self, table_name, factor_str='', field="*"): if factor_str == '': sql = f"select {field} from {table_name}" else: sql = f"select {field} from {table_name} where {factor_str}" self.__cursor.execute(sql) return self.__cursor.fetchone()
def select_many(self, num, table_name, factor_str='', field="*"): if factor_str == '': sql = f"select {field} from {table_name}" else: sql = f"select {field} from {table_name} where {factor_str}" self.__cursor.execute(sql) return self.__cursor.fetchmany(num)
def select_all(self, table_name, factor_str='', field="*"): if factor_str == '': sql = f"select {field} from {table_name}" else: sql = f"select {field} from {table_name} where {factor_str}" self.__cursor.execute(sql) return self.__cursor.fetchall()
def insert(self,table_name, value): sql = f"insert into {table_name} values {value}" try: self.__cursor.execute(sql) self.__conn.commit() print("插入成功") except Exception as e: print("插入失败\n", e) self.__conn.rollback()
def update(self, table_name, val_obl,change_str): sql = f"update {table_name} set" for key, val in val_obl.items(): sql += f" {key} = {val}," sql = sql[:-1]+" where "+change_str try: self.__cursor.execute(sql) self.__conn.commit() print("修改成功") except Exception as e: print("修改失败\n", e) self.__conn.rollback()
def delete(self,table_name, item): sql = f"delete from {table_name} where {item}" try: self.__cursor.execute(sql) self.__conn.commit() print("删除成功") except Exception as e: print("删除失败\n", e) self.__conn.rollback()
|
调用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
| from mysql_normal_util import Database
config = { "host": "127.0.0.1", "port": 3307, "database": "lebo", "charset": "utf8", "user": "root", "passwd": "root" }
db = Database(**config)
select_one = db.select_one("user") print(select_one)
select_many = db.select_many(3, "user") print(select_many)
select_all = db.select_all("user", "id>10") print(select_all)
db.insert("user","(20,'111')")
db.insert("user", "(21,'123'),(22,'456')")
db.update("user", {"name": "222"}, "id=20")
db.update("user", {"id": "23", "name": "12345"}, "id=103")
db.delete("user", "id=23")
|
通过shell命令导出mysql数据
1 2 3 4 5
| /usr/bin/mysql -hclientrecmtagro.db.sxhano.com -urecom_tag_ro -p4BhBsLfEMq3m -P3306 --default-character-set=utf8 -Drecom_tag -A -Ne "select * from t_term_info" > "model/sqlModel.txt” # -h后跟数据库域名 # -u后跟用户 # -p后跟密码 # -D后跟数据库名称
|