導航:首頁 > 編程語言 > pythoncsv寫入資料庫

pythoncsv寫入資料庫

發布時間:2022-06-16 02:08:33

⑴ 利用python如何將數據寫到CSV文件中

如果你的數據是列表格式,可以使用一個迭代器,將數據寫入文件,同時添加必要的分隔符以構成csv文件
如果數據是字典格式,需要考慮使用換行符或者其他特殊符號來分割每個字典元素(包括鍵和值)。鍵和值可以考慮使用和之前不重復的分隔符進行分割。
這樣就構成了一個csv文件(csv使用分隔符分割值的文件)
操作方法如下:
1,使用讀寫追加的方式打開csv文件。
2,找到csv文件的結尾。
3,在結尾使用和之前csv使用的分割相同的格式進行數據添加。
4,關閉文件

⑵ python 怎麼把csv中的數據寫入列表

使用pandas讀取的方法是
pandas.to_csv()
得到的結果是dataframe格式,再用numpy庫轉一下
具體代碼:
import pandas as pd
import numpy as np
file_content = pd.to_csv(r'C:\新建文件夾\result123.csv')
row = np.array(file_content)
lx = row.tolist()

⑶ 用python提取csv文件內容到資料庫

這個腳本可以直接運行,將csv文件放在同級目錄即可。
csv第一列需要有列名,如果csv里沒有列名,需要在代碼中添加列名。
代碼運行示例:python insert.py csvname tablename

⑷ python怎麼寫入csv文件

import pandas as pd#任意的多組列表a = [1,2,3]
b = [4,5,6]

#字典中的key值即為csv中列名dataframe = pd.DataFrame({'a_name':a,'b_name':b})#將DataFrame存儲為csv,index表示是否顯示行名,default=Truedataframe.to_csv("test.csv",index=False,sep='')1234567891011
a_name b_name0 1 41 2 52 3 61234

同樣pandas也提供簡單的讀csv方法
import pandas as pddata = pd.read_csv('test.csv')12

會得到一個DataFrame類型的data,不熟悉處理方法可以參考pandas十分鍾入門
另一種方法用csv包,一行一行寫入
import csv

#python2可以用file替代open
with open("test.csv","w") as csvfile:
writer = csv.writer(csvfile)

#先寫入columns_name
writer.writerow(["index","a_name","b_name"])
#寫入多行用writerows
writer.writerows([[0,1,3],[1,2,3],[2,3,4]])12345678910
index a_name b_name0 1 31 2 32 3 41234

讀取csv文件用reader
import csvwith open("test.csv","r") as csvfile:
reader = csv.reader(csvfile) #這里不需要readlines
for line in reader:
print line

⑸ 如何把大文件的CSV文件寫入MYSQL資料庫

#!/usr/bin/envpython
#coding:utf-8
#
#filename:csv2db.py

importDBUtils.PooledDB
importMySQLdb


defparser(ln):
"""yourbusinesscsvfiledefine"""
returnln.split(",")


defcsvpage(csvfile,pagesize=256):
importcodecs
withcodecs.open(csvfile,'r','utf-8')ashandle:
buff=[]
forlninhandle:
data=parser(ln)
ifdata:
buff.append(data)
iflen(buff)>=256:
todo,buff=buff,[]
yieldtodo


defstore(sql,datas):
conn=conn_pool.connection()
curr=conn.cursor()
curr.execute(sql,datas)
conn.commit()
curr.close()
conn.close()


if__name__=="__main__":
config=loadconfig("dbi.ini")
conn_pool=DBUtils.PooledDB.PooledDB(MySQLdb,2,5,**config)
insert_sql="""insertintotable
(field_id,field_a,field_b)
values(%s,%s,%s)"""
forpageincsvpage("data.csv"):
store(insert_sql,page)

⑹ csv文件怎麼打開 使用Python讀取和寫入CSV文件

csv文件本質上是一個文本文件,具體的讀取和寫入方法有兩種:
直接對csv文件進行文件讀寫操作,每一行是一條記錄,按行讀取即可,簡單代碼如下:
with open("XXX.csv","wr") as f:
f.readline()
f.write()
2.使用第三方庫中的csv文件讀寫函數(本質上還是使用python的文件讀寫方法),如科學計算包pandas包中就有read_csv() to_csv()等函數,其他的一些第三方包里也有,可以自行查詢。
兩種方法各有優劣,第一種方法的優點就是可控性強,但是代碼相對較多,對於python2編碼處理很麻煩;第二種方法的優點是代碼量小,調用方便,處理編碼問題相對容易(在函數中加一個encoding參數即可),但是代碼內部比較復雜,可控性較差

⑺ python 怎麼實現從csv文件中讀取數據 插入到mysql資料庫中

你好,csv格式的和Excel格式的都是差不多的,

下面是讀取Excel的一些函數,希望幫到你:

#-*-coding:cp936-*-
importxlrd3

defgetAllRowsBySheetIndex(sheetIndex,xlsFilePath):
workBook=xlrd3.open_workbook(xlsFilePath)
table=workBook.sheets()[sheetIndex]

rows=[]
rowNum=table.nrows#總共行數
rowList=table.row_values
foriinrange(rowNum):
rows.append(rowList(i))#等價於rows.append(i,rowLists(i))

returnrows

defgetRow(sheetIndex,rowIndex,xlsFilePath):
rows=getAllRowsBySheetIndex(sheetIndex,xlsFilePath)

returnrows[rowIndex]

defgetAllColsBySheetIndex(sheetIndex,xlsFilePath):
workBook=xlrd3.open_workbook(xlsFilePath)
table=workBook.sheets()[sheetIndex]

cols=[]
colNum=table.ncols#總共列數
colList=table.col_values
foriinrange(colNum):
cols.append(colList(i))

returncols

defgetCol(sheetIndex,colIndex,xlsFilePath):
cols=getAllColsBySheetIndex(sheetIndex,xlsFilePath)

returncols[colIndex]

defgetCellValue(sheetIndex,rowIndex,colIndex,xlsFilePath):
workBook=xlrd3.open_workbook(xlsFilePath)
table=workBook.sheets()[sheetIndex]

returntable.cell(rowIndex,colIndex).value#或者table.row(0)[0].value或者table.col(0)[0].value


if__name__=='__main__':
rowsInFirstSheet=getAllRowsBySheetIndex(0,'./產品.xls')
print(rowsInFirstSheet)

colsInFirstSheet=getAllColsBySheetIndex(0,'./產品.xls')
print(colsInFirstSheet)

print(getRow(0,0,'./產品.xls'))#獲取第一個sheet第一行的數據

print(getCol(0,0,'./產品.xls'))#獲取第一個sheet第一列的數據

print(getCellValue(0,3,2,'./產品.xls'))#獲取第一個sheet第四行第二列的單元格的值

⑻ python如何讀取CSV信息存入資料庫

classDBI(object):
"""databaseinterface"""
def__init__(self,conn):
"""keepconnection"""
self._conn=conn
defstore(self,sql,data):
""""""
curr=self._conn.cursor()
curr.executemany(sql,data)
self._conn.commit()
curr.close()
defexecute(self,sql,*args,**kwgs):
"""executesqlondatabase"""
curr=self._conn.cursor()
curr.execute(sql,*args,**kwgs)
self._conn.commit()
curr.close()


defipager(serial,pagesize):
"""makeserialpagebypage"""
buff=[]
forrowinserial:
buff.append(row)
iflen(buff)>=pagesize:
send,buff,=buff,[]
yieldsend
iflen(buff):
yieldbuff


deftester():
importcsv
importsqlite3

dbi=DBI(sqlite3.connect(database=":memory:"))
dbi.execute("createtabletb_tester(id,key,val,tm)")
sql="insertintotb_testervalues(?,?,?,?)"
withopen(todofile,'rb')ashandle:
forrowsinipager(csv.reader(handle),512):
dbi.store(sql,rows)

csv模塊是python處理csv類文件的強大工具; 參考 https://docs.python.org/2/library/csv.html

ipager將大數據流按指定大小分頁, 以節省資源並提升效率;

DBI提供統一的資料庫介面操作方法;

⑼ python 怎麼把csv文件導進資料庫

python 將 csv(中文) 導入mysql 資料庫的簡單代碼
http://blog.csdn.net/u012552296/article/details/50900330

⑽ 如何用python將九九乘法表寫入csv文件中

方法/步驟

閱讀全文

與pythoncsv寫入資料庫相關的資料

熱點內容
證據提取命令視頻 瀏覽:353
java的學習心得 瀏覽:96
prof命令 瀏覽:279
手機加密文件密碼怎麼解開 瀏覽:283
賈躍亭程序員完整視頻 瀏覽:958
怎樣把兩個文件夾打包發送 瀏覽:378
單片機教程資料 瀏覽:982
仿大眾點評系統源碼python 瀏覽:425
手機網路伺服器連接不上是怎麼回事 瀏覽:155
電腦為什麼一直要解壓 瀏覽:530
淘客優惠券網站源碼 瀏覽:555
word轉成pdf在線 瀏覽:775
手機暴力解壓教程 瀏覽:130
解壓小視頻第二期 瀏覽:364
裝機自帶軟體找不到軟體文件夾 瀏覽:330
仙境之路伺服器地址ip 瀏覽:708
華為服務app是什麼東西 瀏覽:180
關於單片機的視頻 瀏覽:592
淘寶直播app緩存怎麼清理 瀏覽:555
android可以刷機嗎 瀏覽:350