Python tempfile NamedTemporaryFile file not found when tried to access it for reading

  mariadb, mysql, python-3.x

Failing to access the temporary csv file and the error that it is giving is MySQLdb._exceptions.InternalError: (2, "File ‘/tmp/tmpc1hsxls9’ not found (Errcode: 2 – No such file or directory)"). Any suggestion regarding it will be highly appreciable.

 tmpfile = None
 with NamedTemporaryFile("wb") as tmpfile:
     self.log.info("Selecting rows from MySql to local file %s...", tmpfile.name)
     self.log.info("select mtime, dpid, route_id, skid, `group`, family, date, sale, dprice, rprice, dcc_price, issue, `return`, memos, vmemos, tlp, cnc, vp, mvp, p, tcc, dcc, ecnc, gt, struc, semi_struc, streetk, mass_hrc, pop_hrc, prem_hrc, kaccounts, ogrocery, snb_cnc, pay_n_go, shop_n_browse, entertainment, outlets, apps_version, updated, visited from daily_sales_msr where date between '"+day+"' and '"+day+"'")

     # self.log.info("select mtime, dpid, route_id, skid, group, family, date, datetime, sale, dprice, rprice, dcc_price, issue, return, memoss, vmemos, tlp, cnc, vp, mvp, p, tcc, dcc, ecnc, gt, struc, semi_struc, streetk, mass_hrc, pop_hrc, prem_hrc, kaccounts, ogrocery, snb_cnc, pay_n_go, shop_n_browse, entertainment, outlets, apps_version, updated, visited from daily_sales_msr where month(date) = month("+month+") and year(date) = year("+month+")")
     # self.log.info(self.sql)

     csv_writer = csv.writer(tmpfile, delimiter='t', encoding='utf-8')
     result = cursor.fetchall()
     self.log.info(result)
     for row in result:
       self.log.info(row)
       csv_writer.writerow(row)
       count += 1

     tmpfile.flush()

 with closing(mysql_destination.get_conn()) as conn:
    with closing(conn.cursor()) as cursor:
      cursor.execute(
       "LOAD DATA LOCAL INFILE '%s' INTO "
       "TABLE %s LINES TERMINATED BY 'rn' (%s)" %
       (tmpfile.name,
        self.mysql_destination_table,
        ", ".join(selected_columns))
       )
       conn.commit()
  tmpfile.close()

Source: Python-3x Questions

LEAVE A COMMENT