【问题标题】:Python read from txt and save into mysqlPython 从 txt 读取并保存到 mysql
【发布时间】:2013-10-05 07:55:39
【问题描述】:

我需要一些关于气象站的帮助。我想将所有结果保存到 mysql 数据库中,但目前我已经将所有结果保存在 txt 文件中。

你能帮我用python写一个脚本,从txt文件中读取并保存到mysql吗?

我的 txt 文件 (temperature.txt) 包含数据和温度。它看起来像:

2013-09-29 13:24 22.60

我正在使用 python 脚本从“result.txt”大文件中获取温度和当前时间:

#!/usr/bin/python

import time



buffer = bytes()

fh = open("/home/style/pomiar/result.txt")

for line in fh:

    pass

last = line

items = last.strip().split()



fh.close();


print time.strftime("%Y-%m-%d %H:%M"), items[1]

但我想将其“打印”到 mysql 表中。我知道如何连接,但我不知道如何将数据保存到表中。

我知道我需要使用: #!/usr/bin/python

import MySQLdb

# Open database connection
db = MySQLdb.connect("localhost","user","password","weather" )

我的数据库“天气”和表“温度”。不知道我是否制作了好表(第一个 - 数据时间,第二个 varchar (5))。现在我需要 python 脚本从这个文件中读取并保存到 mysql 中。

非常感谢您的支持。

【问题讨论】:

  • 向我们展示您到目前为止所做的尝试以及您遇到的问题。我们不是根据一些模糊的要求为您编写代码。

标签: python mysql


【解决方案1】:

下一步很简单:

from contextlib import closing

with closing(self.db.cursor()) as cur:
    cur.execute("INSERT INTO table1(`measured_at`,`temp`) VALUES(%s, %s)", (measured_at,  temp))
    self.db.commit()

附:看起来你问这个问题是因为你没有做作业,也没有通过任何 python 教程阅读如何使用 MySQL。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-06
    • 2015-12-06
    • 1970-01-01
    • 2013-11-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多