Python - 通过变量解析所需数据
Python - parsing through a variable for desired data
这应该很简单。
我正在编写一个程序来从数据库中提取数据以存储在变量中并传递给另一个程序。我让它连接到数据库和 运行 查询以提取数据,该数据在每一列的新行中返回。我想解析此输出以仅将我需要的列存储到单独的变量中,以供另一个 python 程序导入。请注意,打印(出站)部分仅用于测试目的。
函数如下:
def pullData():
cnxn = pyodbc.connect('UID='+dbUser+';PWD='+dbPassword+';DSN='+dbHost)
cursor = cnxn.cursor()
#run query to pull the newest sms message
outbound = cursor.execute("SELECT * FROM WKM_SMS_outbound ORDER BY id DESC")
table = cursor.fetchone()
for outbound in table:
print(outbound)
#close connection
cnxn.close()
这里是我想解析的查询示例输出,因为它当前存储在变量 outbound 中。 (注意)这不是 1 列。这是一行。每一个新行都是数据库中的一个新列...这就是我 运行 程序时它被返回和格式化的方式。
我认为这是实现此目标的最佳方式:
(考虑到您的 table 变量 returns 作为列表)
# Lets say until here you've done your queries
collection = {}
for index,outbound in enumerate(table):
key_name = "key{0}".format(index)
collection[key_name] = outbound
print(collection)
预期输出:
{
"key1" : 6932921,
"key2" : 303794,
...
...
...
}
然后您可以通过添加 return 集合导入 collection 变量来从另一个 python 文件访问它 在你的 pulldata 函数上
在另一个 python 文件上很简单:
from your_file_name import collection # considering they are on the same directory
这应该很简单。 我正在编写一个程序来从数据库中提取数据以存储在变量中并传递给另一个程序。我让它连接到数据库和 运行 查询以提取数据,该数据在每一列的新行中返回。我想解析此输出以仅将我需要的列存储到单独的变量中,以供另一个 python 程序导入。请注意,打印(出站)部分仅用于测试目的。
函数如下:
def pullData():
cnxn = pyodbc.connect('UID='+dbUser+';PWD='+dbPassword+';DSN='+dbHost)
cursor = cnxn.cursor()
#run query to pull the newest sms message
outbound = cursor.execute("SELECT * FROM WKM_SMS_outbound ORDER BY id DESC")
table = cursor.fetchone()
for outbound in table:
print(outbound)
#close connection
cnxn.close()
这里是我想解析的查询示例输出,因为它当前存储在变量 outbound 中。 (注意)这不是 1 列。这是一行。每一个新行都是数据库中的一个新列...这就是我 运行 程序时它被返回和格式化的方式。
我认为这是实现此目标的最佳方式: (考虑到您的 table 变量 returns 作为列表)
# Lets say until here you've done your queries
collection = {}
for index,outbound in enumerate(table):
key_name = "key{0}".format(index)
collection[key_name] = outbound
print(collection)
预期输出:
{
"key1" : 6932921,
"key2" : 303794,
...
...
...
}
然后您可以通过添加 return 集合导入 collection 变量来从另一个 python 文件访问它 在你的 pulldata 函数上
在另一个 python 文件上很简单:
from your_file_name import collection # considering they are on the same directory