[英]Problem writing database data in csv file
我試圖在 python 的幫助下將數據保存在 csv 文件中。 雖然數據正在保存,但當我在終端中運行我的代碼時,它顯示出一些奇怪的模式。 這是我的python代碼
import MySQLdb
import csv
db = MySQLdb.connect(host="localhost", # your host, usually localhost
user="root", # your username
passwd="", # your password
db="getinvolved") # name of the data base
# you must create a Cursor object. It will let
# you execute all the queries you need
cur = db.cursor()
# Use all the SQL you like
cur.execute("SELECT name,phoneNo,email FROM getinvolved")
# print all the first cell of all the rows
dblist=cur.fetchall()
length=len(dblist)-1
lastRow=dblist[length]
print(lastRow[0],lastRow[1],lastRow[2])
fieldname={'name','phoneNo','email'}
with open("emailsend.csv","a") as csvfile:
writer=csv.DictWriter(csvfile,fieldnames=fieldname)
writer.writeheader()
writer.writerow({
"name":lastRow[0],
"phoneNo":lastRow[1],
"email":lastRow[2]
})
**這是我的 csv 文件,顯示隨機模式。 每次我將我的值存儲在其中時,我也會得到一個空行。標題名稱是在玩弄自己 **
name,phoneNo,email
asdsfd,9876543,abc@hotmail.com
phoneNo,email,name
9876543,abc@hotmail.com,asdsfd
email,phoneNo,name
abc@hotmail.com,9876543,asdsfd
email,phoneNo,name
abc@hotmail.com,9876543,asdsfd
name,phoneNo,email
asdsfd,9876543,abc@hotmail.com
name,email,phoneNo
asdsfd,abc@hotmail.com,9876543
我希望它像下面一樣保存我的數據,每次添加新值時沒有任何空白行
name,email,phoneNo
asdsfd,abc@hotmail.com,9876543
name,email,phoneNo
asdsfd,abc@hotmail.com,9876543
name,email,phoneNo
asdsfd,abc@hotmail.com,9876543
{}
創建set()
(或dict()
),它不必保持元素的順序,因此它可以更改行中數據的順序。 更好的用途列表
fieldname = ['name', 'phoneNo', 'email'] # `list` instead of `set` `{}`
在某些系統中,您可能必須使用open(..., newline='')
來跳過新行
with open("emailsend.csv", "a", newline='') as csvfile
在文檔中,您可以在csv.DictWriter 的示例中看到它,並在cvs.reader 中閱讀它並注意
#!/usr/bin/python3
import csv
f = open('names.csv', 'w')
with f:
fnames = ['first_name', 'last_name'] # USE LIST
writer = csv.DictWriter(f, fieldnames=fnames)
writer.writeheader() # WRITE HEADER ONLY ONCE
writer.writerow({'first_name' : 'John', 'last_name': 'Smith'})
writer.writerow({'first_name' : 'Robert', 'last_name': 'Brown'})
writer.writerow({'first_name' : 'Julia', 'last_name': 'Griffin'})
為此目的強烈推薦使用 python pandas :
import pandas as pd
import MySQLdb
import csv
db = MySQLdb.connect(host="localhost", # your host, usually localhost
user="root", # your username
passwd="", # your password
db="getinvolved") # name of the data base
df = pd.read_sql('SELECT name,phoneNo,email FROM getinvolved', con=db)
df.to_csv('emailsend.csv', index=False)
請參閱文檔以格式化數據框。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.