简体   繁体   English

在csv文件中写入数据库数据的问题

[英]Problem writing database data in csv file

I was trying to save data in csv file with the help of python .我试图在 python 的帮助下将数据保存在 csv 文件中。 Though the data is saving it is showing some strange pattern when I run my code in terminal.虽然数据正在保存,但当我在终端中运行我的代码时,它显示出一些奇怪的模式。 this is my python code这是我的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]
        })

**this is my csv file that is showing random pattern. **这是我的 csv 文件,显示随机模式。 And I am also getting an empty row each time I store my value in it.The header name is juggling itself **每次我将我的值存储在其中时,我也会得到一个空行。标题名称是在玩弄自己 **

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


I want it to save my data like below, without any blank row each time I add a new value我希望它像下面一样保存我的数据,每次添加新值时没有任何空白行

name,email,phoneNo
asdsfd,abc@hotmail.com,9876543
name,email,phoneNo
asdsfd,abc@hotmail.com,9876543
name,email,phoneNo
asdsfd,abc@hotmail.com,9876543

{} creates set() (or dict() ) which doesn't have to keep order of elements so it can change order of data in rows. {}创建set() (或dict() ),它不必保持元素的顺序,因此它可以更改行中数据的顺序。 Better uses list更好的用途列表

fieldname = ['name', 'phoneNo', 'email']  # `list` instead of `set` `{}`

In some systems you may have to use open(..., newline='') to skip new lines在某些系统中,您可能必须使用open(..., newline='')来跳过新行

with open("emailsend.csv", "a", newline='') as csvfile

In documentation you can see it in example for csv.DictWriter and read about it in cvs.reader and note在文档中,您可以在csv.DictWriter 的示例中看到它,并在cvs.reader 中阅读它并注意

REFERENCE

#!/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'})

Using python pandas which is highly recommended for this purpose:为此目的强烈推荐使用 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)

Refer to the documentation to format dataframe.请参阅文档以格式化数据框。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM