回家试试程序

 

下面将介绍一个简单的例子来展示如何在pandas中实现对MySQL数据库的读写:

import pandas as pd
from sqlalchemy import create_engine
# 初始化数据库连接,使用pymysql模块
# MySQL的用户:root, 密码:147369, 端口:3306,数据库:test
engine = create_engine('mysql+pymysql://root:123456@localhost:3306/test')
# 查询语句,选出employee表中的所有数据
sql = ''' select * from employee; '''
# read_sql_query的两个参数: sql语句, 数据库连接
df = pd.read_sql_query(sql, engine)
# 输出employee表的查询结果
print(df)

# 新建pandas中的DataFrame, 只有id,num两列
df = pd.DataFrame({'id': [1, 2, 3, 4], 'name': ['zhangsan', 'lisi', 'wangwu', 'zhuliu']})
# 将新建的DataFrame储存为MySQL中的数据表,储存index列
df.to_sql('mydf', engine, index=True)
print('Read from and write to Mysql table successfully!')

将CSV 插入Mysql 数据库

# -*- coding: utf-8 -*-

# 导入必要模块
import pandas as pd
from sqlalchemy import create_engine

# 初始化数据库连接,使用pymysql模块
db_info = {'user': 'root',
           'password': '123456',
           'host': 'localhost',
           'port': 3306,
           'database': 'test'
           }

engine = create_engine('mysql+pymysql://%(user)s:%(password)s@%(host)s:%(port)d/%(database)s?charset=utf8' % db_info, encoding='utf-8')
# 直接使用下一种形式也可以
# engine = create_engine('mysql+pymysql://root:123456@localhost:3306/test')

# 读取本地CSV文件
df = pd.read_csv("C:/Users/fuqia/Desktop/example.csv", sep=',')
print(df)
# 将新建的DataFrame储存为MySQL中的数据表,不储存index列(index=False)
# if_exists:
# 1.fail:如果表存在,啥也不做
# 2.replace:如果表存在,删了表,再建立一个新表,把数据插入
# 3.append:如果表存在,把数据插入,如果表不存在创建一个表!!
pd.io.sql.to_sql(df, 'example', con=engine, index=False, if_exists='replace')
# df.to_sql('example', con=engine,  if_exists='replace')这种形式也可以
print("Write to MySQL successfully!")

 

# -*- coding: utf-8 -*-

# 导入必要模块
import pandas as pd
from sqlalchemy import create_engine

# 初始化数据库连接,使用pymysql模块
db_info = {'user': 'root',
           'password': 'Sess2020!',
           'host': 'localhost',
           'port': 3306,
           'database': 'excel_db'
           }

engine = create_engine('mysql+pymysql://%(user)s:%(password)s@%(host)s:%(port)d/%(database)s?charset=utf8' % db_info, encoding='utf-8')
# # 直接使用下一种形式也可以
# engine = create_engine('mysql+pymysql://root:123456@localhost:3306/test')

# 读取本地CSV文件
df = pd.read_excel(r"C:\Users\86188\Desktop\新建 Microsoft Excel 工作表.xlsx")
print(df)
# 将新建的DataFrame储存为MySQL中的数据表,不储存index列(index=False)
# if_exists:
# 1.fail:如果表存在,啥也不做
# 2.replace:如果表存在,删了表,再建立一个新表,把数据插入
# 3.append:如果表存在,把数据插入,如果表不存在创建一个表!!
pd.io.sql.to_sql(df, 'excel_table', con=engine, index=False, if_exists='append')
# df.to_sql('excel_table', con=engine,  if_exists='replace')   #这种形式也可以
print("Write to MySQL successfully!")

更新语言:

pip install -i https://pypi.tuna.tsinghua.edu.cn/simple --upgrade sqlalchemy --ignore-installed

 

 

 

import os
import re
import shutil
import zipfile
import time
import datetime

def move_rename(oldDocDir=r"E:\workfile\mini line Log\mini_line_module_data - 副本",newDocDir=r"D:\test"):
    '''
    :param oldDocDir: 原始的文件所在文件夹路径;默认r"E:\workfile\mini line Log\mini_line_module_data - 副本"
    :param newDocDir: 将要移动到的文件夹路径;默认 r"D:\test"
    :return:
    将含有物理地址的文件夹的名字,赋予到文件夹内的文件名上,并将所有文件复制到制定的目录(newDocDir)下;
    可以修改正则表达式,来实现其他的功能;
    举例:20032500.XML --> 1C-B7-2C-1F-74-D3_UMT003IA_20032500.XML 并储存在 newDocDir 目录下;
    若之前已经复制过,则跳过;并输出: 举例:Exist:D:\test\00-E0-4C-F1-3A-87\00-E0-4C-F1-3A-87_UMT003IA_20032500.XML

    '''
    # oldDocDir=r"E:\workfile\mini line Log\mini_line_module_data - 副本"
    # newDocDir="D:\\test\\"

    xmlRegex=re.compile(r'[0-9]{8}(.xml)$',re.I)   #文件名的正则表达式,必须是8位数字组成的XML 文件,才能被复制移动;
    phyAddRegex=re.compile(r'\S\S-\S\S-\S\S-\S\S-\S\S-\S\S')  #物理地址的表达式,文件夹中包含物理地址,会被重命名;

    os.chdir(oldDocDir)

    for foldername,subfolders,filenames in os.walk(oldDocDir):

        # print("The current folder is:" + foldername)
        # for subfolder in subfolders:
        #     pass
        phyAdd=phyAddRegex.findall(str(foldername))
        for filename in filenames:
            absdir = os.path.abspath('.')

            if xmlRegex.findall(str(filename)):
                # print(phyAdd,filename)
                baseFolderName=os.path.basename(foldername)
                # print(baseFolderName)
                newName=str(phyAdd[0]) +"_"+ str(baseFolderName)+"_"+filename

                oldName = os.path.join(absdir, phyAdd[0], baseFolderName, filename)
                if os.path.exists(newDocDir):
                    pass
                else:
                    os.mkdir(newDocDir)
                newdir=os.path.join(newDocDir,phyAdd[0])
                newNameDir=os.path.join(newDocDir,str(phyAdd[0]),newName)
                if os.path.exists(str(newdir)):
                    pass
                else:
                    os.mkdir(str(newdir))
                record_list = open(os.path.join(newDocDir, 'record_list.txt'), 'r+')
                record_list_read=record_list.read()                          #检验之前是否已经移动过;
                if newName not in record_list_read:
                    record_list.writelines(newName+'\n')
                    shutil.copyfile(oldName,newNameDir)
                    print("Copy completed!!"+newName)
                else:
                    print("Exist:"+newName)
                record_list.close()



def ZIP_Generition(DocDir=r"D:\test",zipDir=r"D:\test_ZIP"):
    '''
    :param DocDir: 需要压缩的文件,所在的文件夹;默认:D:\test
    :param zipDir: 压缩后的文件所在文件夹;默认:D:\test_ZIP
    :return: 将原文件夹中未被压缩的文件压缩,并保存在指定目录; 压缩文件的文件名为压缩时候的时间;

    '''
    os.chdir(DocDir)
    b = time.localtime()
    DateTime_1 = str(b.tm_year) + "_" + str(b.tm_mon) + "_" + str(b.tm_mday) + "_" + str(b.tm_hour) + "_" + str(
        b.tm_min) + "_" + str(b.tm_sec)
    for foldername,subfolders,filenames in os.walk(DocDir):
        for filename in filenames:
            record_list = open(os.path.join(DocDir, 'ZIP_record_list.txt'), 'r+')
            record_list_read = record_list.read()  # 检验之前是否已经移动过;
            if filename not in record_list_read:
                if os.path.exists(zipDir):
                    pass
                else:
                    os.mkdir(zipDir)
                record_list.writelines(filename + '\n')
                zipnameDir=os.path.join(zipDir,"%s.zip"% (str(DateTime_1)))
                newZip = zipfile.ZipFile(zipnameDir, 'a')
                # newZip = zipfile.ZipFile("..\\test_ZIP\\%s.zip" % (str(DateTime_1)), 'a')
                newZip.write(str(os.path.join(foldername,filename)),compress_type=zipfile.ZIP_DEFLATED)
                newZip.close()
                print("Copy completed!!" + filename)
            else:
                print("Exist:" + filename)
            record_list.close()

    # 上述程序已经包含,不再需要以下判断
    # if os.path.exists('new.zip'):
    #     shutil.move('new.zip',"D:\\test_ZIP\\%s.zip" % (str(DateTime_1)))


move_rename()
ZIP_Generition()

 

posted @ 2020-04-21 18:20  这么神奇  阅读(150)  评论(0编辑  收藏  举报