【问题标题】:My program is supposed to output answers into a csv file with a certain format我的程序应该将答案输出到具有特定格式的 csv 文件中
【发布时间】:2017-01-08 19:14:40
【问题描述】:

这是代码

import datetime

mylist = []
today = datetime.date.today()
mylist.append(today)
print(mylist[0])

file = open('Date.txt', 'a')
file.write(mylist)
file.close()
global timestable
global text
def timestable():
    global name
    name = input("What is your name? ")
    global number
    number = int(input("Insert a number you want the 12 times table for: "))
    global multiply
    for multiply in range(1,13):
        print(number,"x",multiply,"=",number*multiply)
        text()

def text():
    file=open("list.csv","a")
    file.write("The date is," + today + "\nTimestables are:\n" + number + "x" + multiply + "=" + number*multiply + "\nYour name is, " + name)
    file.close()
    text()
timestable()

问题是没有任何东西被输出到文件中,它也应该以某种格式输出。

错误是

Traceback (most recent call last):
  File "D:\Python\Code\Lesson Task Code.py", line 9, in <module>
    file.write(mylist)
TypeError: must be str, not list

【问题讨论】:

  • 错误告诉你该怎么做!最快的方法是file.write(str(mylist)) 或者你使用join 来写一个漂亮的输出(stackoverflow.com/questions/12453580/…
  • python csv module 也可能派上用场...
  • “应该以某种格式输出”。格式是什么?您在 text() 中写的内容与 CSV 格式完全不同,而且一旦您修复当前错误,它就会无限递归并崩溃。

标签: python-3.x csv


【解决方案1】:

您可能想试用time.strftime("%Y-%m-%d"),而不是datetime.date.today()

from time import strftime

today = strftime("%Y-%m-%d")
print(today)

with open('Date.txt', 'a') as file:
    file.write(today+"\n")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-06
    • 1970-01-01
    • 2013-04-01
    • 1970-01-01
    相关资源
    最近更新 更多