python - 解析文本数据并插入MySQL

标签 python mysql parsing

我对编写 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 是我将在程序中唯一填充的内容。解析上述信息并加载到表中的最佳方式是什么?

 CREATE TABLE `test`.`cpu_util_all` (
 `loadid` INT NOT NULL,
  `servername` VARCHAR(45) NOT NULL,
  `date_time` DATETIME NOT NULL,
  `cpu_number` DECIMAL(10,2) NULL,
  `cpu_user` DECIMAL(10,2) NULL,
  `cpu_nice` DECIMAL(10,2) NULL,
  `cpu_system` DECIMAL(10,2) NULL,
  `cpu_wait` DECIMAL(10,2) NULL,
  `cpu_idle` DECIMAL(10,2) NULL,
   PRIMARY KEY (`loadid`, `servername`, `date_time`,`cpu_user`));

最佳答案

您可以使用 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 .

关于python - 解析文本数据并插入MySQL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31548317/

相关文章:

python - 来自相关包的未知 python 导入行为

python - 换行原始字符串

python - 如何在反向传播算法中使用链式法则的结果中的矩阵相乘

python : How to write list to csv with N items per row

PHP分页类

Java源代码解析器: Need to find access modifiers of declared field variables

java - 在保留其结构的同时过滤 XML

php - 生成不重复的配对组,php 和 mysql

php - 查询正常工作但在准备好的语句中不工作

javascript - Js Number.parseInt 函数中的一些奇怪行为,有人可以解释一下吗?