简体   繁体   English

Python3:无法使用从 SQL 表中获取的数据写入文本文件

[英]Python3: Can't write to text file with obtained data from SQL table

I think I am stucked on an easy job as a beginner but have to ask this question.我想我作为初学者被困在一份轻松的工作中,但不得不问这个问题。 My objective is to create another list from data obtained from a SQL Table.我的目标是根据从 SQL 表中获得的数据创建另一个列表。 This list will be created in acocrdance with the input data by user.该列表将根据用户输入的数据创建。

The SQL table has no problem, but I couldn't write on a txt file despite not receiving an error message. SQL 表没有问题,但我无法在 txt 文件上写入,尽管没有收到错误消息。 Where is the problem?问题出在哪里?

import sqlite3
db = sqlite3.connect("air2.sql")
cs = db.cursor()


epcs = dict()
for i in range(19):
    epcs[i] = 0

def addepc():

    epcNo = input("EPC No:")
    a = "SELECT * FROM 'epcval5' WHERE epc='EPC{}'".format(epcNo)

    cs.execute(a)
    data = cs.fetchone()
    print("You have selected this EPC:")
    for i in data:
        print(i)

    b = "SELECT value FROM 'epcval5' as float WHERE epc='EPC{}'".format(epcNo)
    cs.execute(b)
    epcv = cs.fetchone()
    res = str('.'.join(str(ele) for ele in epcv))
    print(type(res))

    with open('epcs.txt', 'w') as f:
        epcs[epcNo] = res
        f.write(epcs[epcNo])

addepc()
        print("Done! Press ENTER to continue")

        input()

You could use pandas to write it to a csv file您可以使用 pandas 将其写入 csv 文件

with sqlite3.connect(DB_FILENAME) as con:
    df = pd.read_sql_query('your sql query',con)

df.to_csv('file_name')

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

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