
如何优雅地将dat,txt 或者excel 文件导入python
1个回答
展开全部
为什么一定要用python呢,你用excel写一条公式,类似于:
=array('filter'=>"&A&")
然后按住右下角的十字架,一直往下拖,一堆数组就出来了,然后用php写进去就好了
#-*- coding: utf-8 -*-
#encoding=utf-8
import MySQLdb
import xlrd
#打开excel
data = xlrd.open_workbook('testpython.xls')
#根据名字拿到excel的某个表
table = data.sheet_by_name('Sheet1')
#行数
nrows = table.nrows
for rownum in range(1,nrows):
row = table.row_values(rownum)
print len(row)
# 打开数据库连接
db = MySQLdb.connect("localhost","root","","pythonmysql" )
#链接资源
cursor = db.cursor()
# SQL 插入语句
sql = 'insert into pyuser (username,password, email, qq) values("%s", "%s","%s","%s")' % \
(row[0],row[1],row[2],row[3])
print sql
try:
# 执行sql语句
cursor.execute(sql)
# 提交到数据库执行
db.commit()
except:
db.rollback()
# 关闭数据库连接
db.close()
=array('filter'=>"&A&")
然后按住右下角的十字架,一直往下拖,一堆数组就出来了,然后用php写进去就好了
#-*- coding: utf-8 -*-
#encoding=utf-8
import MySQLdb
import xlrd
#打开excel
data = xlrd.open_workbook('testpython.xls')
#根据名字拿到excel的某个表
table = data.sheet_by_name('Sheet1')
#行数
nrows = table.nrows
for rownum in range(1,nrows):
row = table.row_values(rownum)
print len(row)
# 打开数据库连接
db = MySQLdb.connect("localhost","root","","pythonmysql" )
#链接资源
cursor = db.cursor()
# SQL 插入语句
sql = 'insert into pyuser (username,password, email, qq) values("%s", "%s","%s","%s")' % \
(row[0],row[1],row[2],row[3])
print sql
try:
# 执行sql语句
cursor.execute(sql)
# 提交到数据库执行
db.commit()
except:
db.rollback()
# 关闭数据库连接
db.close()
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询