【问题标题】:How to write a listbox's data in a file.txt如何将列表框的数据写入 file.txt
【发布时间】:2019-11-15 11:47:24
【问题描述】:

我无法将我在名为"dovutolist" 的列表框中看到的记录写入名为"nuovo_file" 的文件中。文件已创建,但不写入任何数据。

代码是这个:

   def Salva_File():
        percorso_file=tkinter.filedialog.asksaveasfile().name
        lista=list(dovutolist.get(0,END))
        print(lista)
        nuovo_file=open(percorso_file,"w")

        for i in range(len(lista)):
            nuovo_file.write(lista[i]+'\n')
        nuovo_file.close

我得到的错误是这个:

nuovo_file.write(lista[i]+'\n')
TypeError: can only concatenate tuple (not "str") to tuple

你能帮帮我吗?

【问题讨论】:

  • 使用 print( lista[i] ) 检查变量中的内容 - 错误表明这是元组,而不是字符串。也许你必须从这个元组中得到一个元素 - 即。 lists[i][0]lists[i][1].
  • 顺便说一句:你可以使用 for i in range(len(lista)): write( lists[i] ) 而不是 for item in lista: write( item ) - 它更具可读性。
  • 顺便说一句:您不必转换为列表来保存它。而你在nuovo_file.close() 中忘记了()
  • 如果您使用asksaveasfile,则无需调用open,文件会自动为您打开。
  • 视频中的打印(列表)给了我 [(1, '2015', '04070870870', 'RESTAURANT A CASA DI SALVO AND LUCA DI SAPIENZA S & VIA FONDACO 4 BELPASSO', '41 . 60')]

标签: python list sqlite tkinter python-3.6


【解决方案1】:

经过这么多测试,我设法解决了,至少绕过了障碍,我得到了我想要的,这是代码:

def isiDovuto_stampa():
percorso_file = tkinter.filedialog.asksaveasfile ().name
nuovo_file = open (percorso_file, "w")
conn = sqlite3.connect('isi_dovuto.db')
with conn:
    cursore = conn.cursor()
    cursore = conn.cursor()
    cursore.execute("SELECT * FROM isi_dovuto")
    while True:
        # fin tanto che True è vero, cioè il ciclo apparentemente non termina mai ...
        # as long as True is true, that is the cycle apparently never ends ...
        righe = cursore.fetchall()

        if len(righe) > 0:
        # se abbiamo delle righe, le stampa
        # if we have lines, press
            for riga in righe:

                #print(riga)
                nuovo_file.write(str(riga)+'\n''\n')

            else:
        # altrimenti interrompe forzatamente il ciclo while
        # otherwise it forcibly interrupts the while loop
                break
nuovo_file.close ()

return righe

【讨论】:

    【解决方案2】:

    您必须将文件名写在引号中:

    例如:

    nuovo_file=open('file_name.txt','w')
    

    您还应该知道,write(w) 也会在您下次进入程序时覆盖所有数据。您可以使用 append (a+) 多次写入。这会保留以前的数据。

    【讨论】:

    • “你必须把文件名写在引号里” 不是一个真实的陈述。 OP 正在使用一个变量,这非常好。
    猜你喜欢
    • 2020-06-01
    • 1970-01-01
    • 2022-11-10
    • 1970-01-01
    • 2016-01-20
    • 2019-03-13
    • 2020-11-23
    • 1970-01-01
    • 2019-02-22
    相关资源
    最近更新 更多