python读取本地文件夹中文件内容并存取到数据库中

主要代码

工作中有一个需求是需要将文件夹中所有的文件内容读取,含标题及具体内容一起存储到数据库中,在网上查阅了一些资料,都只能获取文件夹中文件名,不能获取具体的内容。最后自己也参考了别人的代码最后完成了这个效果,大致是将文件也作为一种文件夹,进行迭代的方法写

import os
import pymysql
import  re
def check_file(path):
    if not os.path.exists(path):
        print("File not exist")
        return False
    if (os.path.isdir(path)):
        # 操作文件夹
        if not os.access(path, os.R_OK):
            print("File is accessible to read")
            return False

        # todo
        print(os.path.basename(path))

        for file in os.listdir(path):
            file = os.path.join(path, file)
            check_file(file)
    else:
        # 操作文件
        if not os.access(path, os.R_OK):
            print("File is accessible to read")
            return False
        with open(path,encoding='utf-8') as f:
            # todo
            #获取路径名称
            #f.name
            #获取文件名称
            name=os.path.basename(path)
            #去掉文件后缀名
            title=os.path.splitext(name)[0]
            #去掉点和数字
            str = re.sub('[a-zA-Z0-9’!"#$%&\'()*+,-./:;<=>?@,。?★、…【】《》?“”‘’![\\]^_`{|}~\s]+', "", title)
            conn = pymysql.connect(
                host='localhost',
                port=3306,
                user='root',
                passwd='123456',
                db='acticles',
                charset='utf8',
            )
            cur = conn.cursor()
            line = f.read()
            f.close()
            print(line)
            cur.execute(
                  "insert into test"
            ""
            " (title,content) values(%s,%s)",
            [str,line,])
            cur.close()
            conn.commit()
            print('执行数据库')
            conn.close()

if __name__ == '__main__':

    check_file(r'C:\Users\Administrator.USER-20211209NL\Desktop\测试')

运行效果截图:

数据库
在这里插入图片描述
运行结果
在这里插入图片描述

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值