Python 如何编写列表框';将数据保存在file.txt中

Python 如何编写列表框';将数据保存在file.txt中,python,list,sqlite,tkinter,python-3.6,Python,List,Sqlite,Tkinter,Python 3.6,我无法在名为“nuovo_file”的文件中写入我在名为“dovutolist”的列表框中看到的记录。该文件已创建,但不写入任何数据 代码如下: def Salva_File(): percorso_file=tkinter.filedialog.asksaveasfile().name lista=list(dovutolist.get(0,END)) print(lista) nuovo_file=open(percors

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

代码如下:

   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
我得到的错误是:

   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

你能帮我吗?

你必须用引号写下文件名:

例如:

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

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

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

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

使用
print(lista[i])
检查变量中的内容-错误显示为元组,而不是字符串。也许你必须从这个元组中获取一个元素,例如,
lists[i][0]
lists[i][1]
。顺便说一句:对于范围内的i(len(lista)):write(lists[i])你可以对列表中的项使用-
,它更可读。顺便说一句:你不必转换到列表来保存它。你忘记了
()
nuovo_file.close()
中。如果你使用
asksaveasfile
,你不需要调用
打开
,文件将自动为你打开。视频中的打印(列表)给我[(1,'2015,'04070870,'A CASA DI SALVO And LUCA DI SAPIENZA S&VIA FONDACO 4 BELPASSO,'41.60')]“您必须在引用标记中写入文件名”不是正确的语句。OP使用的是一个变量,这很好。