需求

我们有很多个文件 a.txt , b.txt , c.txt …..

这些文件里面有很多数据,表示a对应的一些数据内容,比如a文件里面有以下内容

a.txt

1
2
3
4
5
小米
华为
OPPO
vivo
魅族

整理成sql 就是

1
2
3
4
5
insert into table (type,brand) value('a','小米');
insert into table (type,brand) value('a','华为');
insert into table (type,brand) value('a','OPPO');
insert into table (type,brand) value('a','VIVO');
insert into table (type,brand) value('a','魅族');

如此工作重复且麻烦,所以用python的语法简单处理一下

python 代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
import os
# 获取文件目录列表
files = os.listdir(r'CUsersLengffDesktoptemp');
for file in files
# 拼接文件目录地址,获取文件对象信息(此处需要注意文件编码方式)
of = open(CUsersLengffDesktoptemp+file,encoding='UTF-8');
# 遍历文件内容
for text in of.readlines()
# 根据文件名称 和遍历出来的内容拼接SQL语句
key = insert into table (type,brand) value( '%s', '%s'); % (file.replace('.txt',''),text.strip('n'));
# strip 是为了去除读取每行的回车符
# 输出日志
print(key)

扩展

如此一来我们便能轻松获取文件里面对应的信息,当我们需要得到打印信息变成一个文件的时候,可以python 打印日志

1
2
python get.py  my.sql