异常

  1. import traceback
  2. try:
  3. pass
  4. except Exception:
  5. traceback.print_exc()

操作数据库

  1. # pip install PyMySQL
  2. import pymysql
  3. db = pymysql.connect(host='127.0.0.1', user='root', password='', database='test', charset='utf8mb4')
  4. cursor = db.cursor()
  5. for word in words_list:
  6. try:
  7. cursor.execute('select id from forbidden_words where words = %s limit 1', (word,))
  8. result = cursor.fetchone()
  9. try:
  10. if result is None:
  11. cursor.execute('insert into forbidden_words(words) values (%s)', (word,))
  12. db.commit()
  13. except:
  14. print("写入失败")
  15. db.rollback()
  16. except:
  17. print("查询失败")
  18. db.close()

创建临时文件

  1. tmp_file = tempfile.TemporaryFile("r+")
  2. tmp_file.write(open("file_name", encoding="utf-8").read())
  3. tmp_file.seek(0)

获取文件名和后缀

  1. # input/a.csv
  2. fileArr = os.path.splitext(os.path.basename(inputFile))
  3. # fileArr[0] a
  4. # fileArr[1] .csv