写一段Python代码,能将txt文件转换为csv文件并插入进MySQL
时间: 2024-05-02 21:21:54 浏览: 131
以下是一段Python代码,可以将txt文件转换为csv文件并插入到MySQL数据库中:
```python
import csv
import mysql.connector
# Connect to MySQL database
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="yourdatabase"
)
mycursor = mydb.cursor()
# Open the txt file and create a csv writer
with open('data.txt', 'r') as txtfile:
with open('data.csv', 'w', newline='') as csvfile:
csvwriter = csv.writer(csvfile)
# Read each line of the txt file and write to the csv file
for line in txtfile:
line = line.strip().split('\t')
csvwriter.writerow(line)
# Insert the data from the csv file into MySQL database
with open('data.csv', 'r') as csvfile:
csvreader = csv.reader(csvfile)
next(csvreader) # Skip the header row
for row in csvreader:
sql = "INSERT INTO yourtable (column1, column2, column3) VALUES (%s, %s, %s)"
val = (row[0], row[1], row[2]) # Adjust column names and number of columns as needed
mycursor.execute(sql, val)
mydb.commit()
```
请注意,此代码仅是示例。您需要更改代码中的主机名、用户名、密码、数据库名、数据文件名、表名和列名,以使其适合您的实际情况。
阅读全文