将csv导入mysql:文件名作为列中的值

时间:2018-11-13 09:14:14

标签: python mysql csv

我有一个名为2018-10-18_trx_result.csv2018-10-11_another-file.csv的文件。如何将我的文件名作为date format列中的值??

示例:我导入2018-10-18_trx_result.csv,因此2018-10-18应该是我的date_sourced列中的值,如下所示:

|date_sourced| sha1 | vsdt | trendx |notes|
-------------------------------------------
|2018-10-18  | SHA1 | vsdt | trendx |notes| #how can I remove the headers too?
|2018-10-18  | value| value| value  |value|
|2018-10-18  | value| value| value  |value|

这是将我的csv导入mysql数据库的代码:

import csv
import mysql.connector

mydb = mysql.connector.connect(user='root', password='',
                          host='localhost',
                          database='jeremy_db')
file = open('C:\\Users\\trendMICRO\\Desktop\\OJT\\test.csv', 'rb')  
csv_data = csv.reader(file)

cursor = mydb.cursor()

for row in csv_data:
    cursor.execute('INSERT INTO jeremy_table_test(sha1, vsdt,trendx,notes )' 'VALUES(%s, %s, %s,%s)',row)

# close the connection to the database.
mydb.commit()
cursor.close()
print("Done")

当我将标题上传到表中时,如何排除标题?

1 个答案:

答案 0 :(得分:0)

这可以帮助您。使用'regular expression're

import re
fileName=['2018-10-18_trx_result.csv','2018-10-11_another-file.csv']
for m in fileName:
    print [re.findall("([0-9]{4}\-[0-9]{2}\-[0-9]{2})", m)[0], m]

结果:

['2018-10-18', '2018-10-18_trx_result.csv']
['2018-10-11', '2018-10-11_another-file.csv']