简体   繁体   中英

Importing csv to mysql: file name as value in column

I have a file named: 2018-10-18_trx_result.csv and 2018-10-11_another-file.csv . How can I make my filename as value inside my column as date format ?.

Example: I import 2018-10-18_trx_result.csv so 2018-10-18 should be the value in my date_sourced column like this:

|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|

Here is my code to import my csv to mysql database:

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")

Also how can I exclude the headers when I upload them to my table?.

This can help. Use ' 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]

result:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM