怎么将csv文件导入python导入csv文件 然后对导入的文件进行聚类分析

csv文件怎么打开 使用Python读取和写入CSV文件_百度知道python读取csv文件
python读取csv文件
发布时间: 20:21:00
编辑:www.fx114.net
本篇文章主要介绍了"python读取csv文件 ",主要涉及到python读取csv文件 方面的内容,对于python读取csv文件 感兴趣的同学可以参考一下。
csv文件很方便读取。我们公司的运营部最近要面对新项目上线,需要导入很多数据批量到数据库中。无疑的,csv是个很好的选择。下面是我写的一个读取csv文件的方法,使用的是python2.7.5:
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
4 # @Author
: /YeRuGeMiMi
6 # @Version : 1.0
8 #CSV文件的操作工具类
9 #环境:python 2.7.5
10
11 import os.path
12
14 #csv_get_lines 读取CSV文件中指定行的数据,使用的是第一行是title的格式
15 #param: csvfile csv文件路径
16 #param:lines 读取指定行数
17 #param: offset 开始行数
18 #param: sign 分隔符
19 #return: []
20 def csv_get_lines(csvfile,lines,offset=0,sign=','):
21
#判断文件是否存在
22
if not os.path.exists(csvfile) :
23
return False
24
f=open(csvfile,'r')
25
datas=[]
28
for line in f :
29
#读取title
30
if i == 0:
31
line=line.strip('\n')
32
titles=line.split(sign)
33
#跳到指定的开始行
35
if i&offset :
37
continue
38
#以[{title:data,title:data,title:data}]的格式输出数据
40
if j&lines :
41
line=line.strip('\n')
43
data=line.split(sign)
44
#判断文件的格式是否正确
45
if not len(titles) == len(data) :
46
return False
47
datas.append(dict(zip(titles,data)))
49
return datas
这个方法对于格式的检查还是太差了,我仅仅只对数目进行了检查。恩,过个几天再增强一下。或许应该讲检查抽取成另一个方法。这个方法,我还用java实现了。就不贴出来,感兴趣的,可以访问我的github:
本文标题:
本页链接:当前位置:&>&&>&&>&
python读取csv文件的例子
发布时间:编辑:
python读取csv文件的小例子,学习下python操作csv的方法,有研究python编程的朋友做个参考。
例子,读取csv文件。
复制代码 代码示例:
import csv
for line in open(&test.csv&):
name,age,birthday = line.split(&,&)
name = name.strip(' \t\r\n');
age = age.strip(' \t\r\n');
birthday = birthday.strip(' \t\r\n');
print (name + '\t' + age + '\t' + birthday)
csv文件内容格式如下:
alice, 22,
与 python读取csv文件的例子 有关的文章
本文标题:
本页链接:
12345678910
12345678910> python写Mysql数据库的问题问题描述:我想将一个csv文件导入数据库,在导入的时,首先查询
python写Mysql数据库的问题问题描述:我想将一个csv文件导入数据库,在导入的时,首先查询
muzhongmei & &
发布时间: & &
浏览:92 & &
回复:0 & &
悬赏:0.0希赛币
python写Mysql数据库的问题问题描述: &
我想将一个csv文件导入数据库,在导入的时,首先查询expinfo表,得到最后一条记录的id,然后在将当前csv数据写入数据表expdata时,用前面得到的id填充expdata表的exp_id域。举个例子:csv数据:1,2,3expdata表 x,y,z,exp_id &
1,2,3,idexpdata表的定义如下:  SQL code   CREATE
TABLE IF NOT EXISTS `Experiment`.`expdata` (
`expdata_id` INT NOT NULL AUTO_INCREMENT ,
`exp_id` INT NULL ,
`x` FLOAT NULL ,
`y` FLOAT NULL ,
`z` FLOAT NULL ,
`angle01` FLOAT NULL ,
`angle02` FLOAT NULL ,
`angle03` FLOAT NULL ,
PRIMARY KEY (`expdata_id`) ) ENGINE = InnoDB;
python代码是以一个网上找到的代码段为基础改的:  Python code   #!/usr/bin/env python
# Run with no args for usage instructions # # Notes: #
- will probably insert duplicate records if you load the same file twice #
- assumes that the number of fields in the header row is the same #
as the number of columns in the rest of the file and in the database #
- assumes the column order is the same in the file and in the database # # Speed: ~ 1s/MB #
# usage: # #
csv2db.py root financial csvtable Book1.csv # # # import sys import MySQLdb import csv import os
def main(user, db, table, csvfile):
conn = getconn(user, db,)
except MySQLdb.Error, e:
print &Error %d: %s& % (e.args[0], e.args[1])
sys.exit (1)
cursor = conn.cursor()
id1 = getExpId(conn,cursor)
print &last id from getExpId is %d& % id1
loadcsv( conn,cursor, table, csvfile,id1)
cursor.close()
conn.close()
def getconn(user, db, passwd=&&):
conn = MySQLdb.connect(host = &localhost&,
user = user,
passwd = &521521&,
return conn
def getExpId(conn, cursor):
''' get the last item's id in the tbincome table'''
''' so we can insert the csv data to the csvtable '''
cursor.execute(&select max(exp_id) from expinfo&)
except MySQLdb.Error, e:
print &Error %d: %s & %(e.args[0],e.args[1])
id = cursor.fetchone()
print &last id in expinfo is %d& % id
def nullify(L):
&&&Convert empty strings in the given list to None.&&&
# helper function
if(x == &&):
return None
return [f(x) for x in L]
def loadcsv(conn,cursor, table, filename,_exp_id):
Open a csv file and load it into a sql table.
Assumptions:
- the first line in the file is a header
f = csv.reader(open(filename))
header = f.next()
numfields = len(header)
query = buildInsertCmd(table, header,_exp_id,numfields)
for line in f:
vals = nullify(line)
vals.append(_exp_id[0])
print len(vals)
for x in vals:
cursor.execute(query, vals)
except MySQLdb.Error, e:
print &Error %d: %s & %(e.args[0],e.args[1])
def buildInsertCmd(table, header, _exp_id, numfields):
Create a query string with the given table name and the right
number of format placeholders.
$>>$ buildInsertCmd(&foo&, 3)
'insert into foo values (%s, %s, %s)'
assert(numfields & 0)
placeholders = (numfields) * &%s, & + &%s&
header.append('exp_id')
query = (&insert into %s & % table) + (&(%s)& %header) +(& values (%s)& % (placeholders))
print query
return query
if __name__ == '__main__':
# commandline execution
args = sys.argv[1:]
if(len(args) & 4):
print &error: arguments: user db table csvfile&
sys.exit(1)
main(*args)
本问题标题:
本问题地址:
温馨提示:本问题已经关闭,不能解答。
暂无合适的专家
&&&&&&&&&&&&&&&
希赛网 版权所有 & &&

我要回帖

更多关于 python 聚类分析 的文章

 

随机推荐