简体   繁体   English

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

[英]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 .我有一个名为: 2018-10-18_trx_result.csv2018-10-11_another-file.csv How can I make my filename as value inside my column as date format ?.如何将我的文件名作为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:示例:我导入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|

Here is my code to import my csv to mysql database:这是我将 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")

Also how can I exclude the headers when I upload them to my table?.另外,当我将标题上传到我的表格时,如何排除标题?。

This can help.这可以提供帮助。 Use ' regular expression ' re .使用' 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']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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