在MySQL中解析文本数据并插入

2024-04-24 23:46:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我对编写python/任何需要在以下情况下处理的脚本的方法感到困惑。在

我从服务器生成一个包含列名、时间戳、服务器名和列值的文本文件

cpunumber   1437501780  l09fr01 40.0
cpunice 1437501780  l09fr01 0.0
cpusystem   1437501780  l09fr01 0.0
cpuwait 1437501780  l09fr01 0.0
cpuuser 1437501780  l09fr01 1.0
cpudile 1437501780  l09fr01 0.0

我需要插入这些值的表格如下所示。加载id是我将在程序中唯一填充的内容。解析上述信息并将其加载到表中的最佳方法是什么?在

^{pr2}$

Tags: 方法服务器脚本时间情况表格文本文件列值
1条回答
网友
1楼 · 发布于 2024-04-24 23:46:34

您可以使用pandas来读取这样的数据,并将其写入SQL。在

import pandas as pd
import sqlite3

## Tweak the options here to match the exact file format.  
x = pd.read_table('test.txt') 
## add column names (not necessary if the file has a header)
x.names = ['loadid','servername','date_time','cpu_number','cpu_nice','cpu_system','cpu_wait','cpu_idle']

## create SQL connection.
con = sqlite3.connect('test.db',)
## tweak the options here to get the keys and constraints.
x.to_sql('test', con)

您可以阅读有关使用pandas进行阅读和写作的更多信息here。在

相关问题 更多 >