【问题标题】:save list to CSV - python将列表保存到 CSV - python
【发布时间】:2013-07-24 13:18:59
【问题描述】:

我尝试使用“导入 csv”将我的输出保存为 csv,但只会出错。有什么原因吗?

由于我无法使其运行,它还会通知文件是否已存在?

非常感谢

from tkinter import *
from tkinter.filedialog import asksaveasfilename
from tkinter import ttk

import csv

def data():
  ...
  output= <class 'list'>  #just an example
  ...    

def savefile():
  name= asksaveasfilename()
  create = csv.writer(open(name, "wb"))
  create.writerow(output)
  for x in output:
      create.writerow(x)

root = Tk()
Mframe = ttk.Frame(root)
Mframe.grid(column=0, row=0, sticky=(N, W, E, S))

bSave=ttk.Button(Mframe, text='Save File', command=savefile)
bSave.grid(column=1, row=0)

root.mainloop()

【问题讨论】:

  • "...只会出错"。有什么错误?
  • 错误:“TypeError: 'str' 不支持缓冲区接口”

标签: csv python-3.x tkinter


【解决方案1】:

您正在打开文件,但没有关闭它。一个好的做法是使用 with 语句确保关闭它。顺便说一句,我不知道output 列表如何,但如果它不是列表列表,我更应该调用一次writerow

另外,要确保这个列表也是一个全局变量,否则在savefile的范围内是不可用的。但是,全局变量并不是一个很好的解决方案,因此请考虑将其作为参数传递给savefile 或使用一个类来保存所有这些数据:

def savefile():
    name = asksaveasfilename()
    with open(name, 'w', newline='') as csvfile:
        create = csv.writer(csvfile)
        create.writerow(output)

【讨论】:

  • 谢谢。我将其更改为您建议的函数,并收到此错误“TypeError:'str'不支持缓冲区接口”。你能解释一下为什么吗?
  • @user2613527 在 Python 3 中,二进制模式无法写入 csv 文件。根据documentation,你应该使用open(name, 'w', newline='')(我已经更新了答案)。
  • 非常感谢。它几乎是完美的。列表中的 str 写在一行中,但写在不同的单元格中,而不是逐行写入。我不知道为什么?文件不是以 CSV 扩展名保存的,如何使用 name=name+'.csv' 添加它会导致我的问题如果我需要覆盖一个文件将无法正常工作。
  • 已解决(NL 表示换行): name = asksaveasfilename() NL output_file = open(name, 'w', newline='') NL data = csv.writer(output_file) NL for row在输出中:NL data.writerow([row]) NL output_file.close()
猜你喜欢
  • 2016-05-17
  • 2016-01-05
  • 1970-01-01
  • 2021-11-28
  • 2021-07-04
  • 2016-03-14
  • 1970-01-01
  • 2016-12-09
  • 1970-01-01
相关资源
最近更新 更多