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