2017-07-27 187 views
0

我有一张名为'CompanyData'的表,其中包含各公司的数据。我需要将数据存储在与每个公司名称对应的文件中。如何基于python中的数据库数据创建文件?

列是

c_emp_id, name, ph, email, company_name, country 

我如何能解决使用Python

问题

我尝试:

import os 
import pymysql 

user = '***' 
password = '***' 
host = '***' 
db= '***' 

connection = pymysql.connect(host, user, password, db) 
cursor = connection.cursor() 
query = "select * from CompanyData" 
cursor.execute(query) 
results = cursor.fetchall() 
for value in results: 
    filename = "{}.txt".format(value[4]) 
    if os.path.isfile(filename) 
     fh = open(filename, 'w') 
    string1 = "{}-{}-{}\n".format(value[1], value[2], value[3]) 
    if 'fh' in locals(): 
     fh.write(string1) 

我在这里简化了我的问题,使人们可以理解问题。

回答

3

这是一个使用pandas的解决方案。关键是按公司名称对数据进行分组,然后将每个组保存到不同的文件中。

import pandas as pd 
df = pd.DataFrame({'name': ['A', 'B', 'C'], 'company': ['AAA', 'BBB', 'AAA']}) # Example of data 

#  company name 
# 0  AAA A 
# 1  BBB B 
# 2  AAA C 

groups = df.groupby('company') 
for company, group in groups: 
    group.to_csv('{0}.txt'.format(company), sep='-') 

在这个例子中,两个文件将被创建:AAA.txtBBB.txt。这些文件的内容将是:

-company-name 
0-AAA-A 
2-AAA-C 

-company-name 
1-BBB-B 

为了你的mysql数据库转换为大熊猫数据框,您可以执行以下操作:

import mysql.connector as sql 
import pandas as pd 

db_connection = sql.connect(host='hostname', database='db_name', user='username', password='password') 
df = pd.read_sql('SELECT * FROM table_name', con=db_connection) 
+0

我还没有使用熊猫模块。那么你能告诉我怎样才能把我的数据__结果___转换成__数据框___。 – Arijit

+0

@Arijit看到我的新答案(这应该工作,但我没有测试过) –

+0

在输出文件中,我得到所有逗号分隔的列。但我需要格式化输出。如__string1 =“{} - {} - {} \ n”.format(value [1],value [2],value [3]))__。你能帮我解决这个问题吗? – Arijit

1

我是不确定“group by”是否可以帮助,但我可以尝试用代码来帮忙。

首先收集一个字典中的公司的所有数据,然后执行写入,也尝试使用“打开”的“with”语句,这将处理文件的关闭。

import os 
import pymysql 

user = '***' 
password = '***' 
host = '***' 
db= '***' 

connection = pymysql.connect(host, user, password, db) 
cursor = connection.cursor() 
query = "select * from CompanyData" 
cursor.execute(query) 
results = cursor.fetchall() 
company_data = {} 

# collect data into a dict 
for value in results: 
    company = value[4] 
    try: 
     current_data = company_data[company] 
     current_data += "\n" + "-".join([value[1], value[2], value[3]]) 
     company_data[company] = current_data 
    except KeyError: 
     current_data = "-".join([value[1], value[2], value[3]]) 

# write the data into the file 
for company, data in company_data.iteritems(): 
    filename = "%s.txt" % company 
    with open(filename, 'w') as fh: 
     fh.write(data) 

保存到字典可能创建了大量中间弦(current_data + = “\ n” + “ - ”。加入([值[1],值[2],值[3]]) );不确定下面的使用列表是否是更好的实现。

# collect data into a dict 
for value in results: 
    company = value[4] 
    try: 
     current_data = company_data[company] 
     # since lists are mutable we do not need to re-assign this back to dict 
     current_data.append("-".join([value[1], value[2], value[3]]) 
    except KeyError: 
     current_data = "-".join([value[1], value[2], value[3]]) 

# write the data into the file 
for company, data in company_data.iteritems(): 
    filename = "%s.txt" % company 
    with open(filename, 'w') as fh: 
     for line in data: 
      fh.write(line + "\n")