创建一个将列表保存到.txt文件的功能

时间:2014-03-30 05:48:21

标签: python list file function

我正在尝试编写一个函数来保存通过以原始格式读回.txt文件而创建的列表。

以这种格式生成列表的代码:

(datetime.datetime(2014,2,28,0,0),'tutorial signons')

从.txt文件的格式:

“教程登录,28/02/2014”

DATE_FORMAT = '%d/%m/%Y'
import datetime
def as_datetime(date_string):
    try:
        return datetime.datetime.strptime(date_string, DATE_FORMAT)
    except ValueError:
        # The date string was invalid
        return None

def load_list(filename):
    new_list = []
    with open(filename, 'rU') as f:
        for line in f:
            task, date = line.rsplit(',', 1)
            try:
                # strip to remove any extra whitespace or new lines
                date = datetime.datetime.strptime(date.strip(), DATE_FORMAT)
            except ValueError:
                continue #go to next line
            new_list.append((date,task))
    return new_list

尝试将“todolist”保存为新的“文件名”的功能:

def save_list(todolist, filename):
    with open('todo.txt', 'w') as f:
        print>>f.write("\n".join(todolist))

使用所需的输入:

>>>save_list(load_list('todo.txt'), 'todo2.txt')

返回此错误:

Traceback (most recent call last):
  File "<pyshell#127>", line 1, in <module>
    save_list(load_list('todo.txt'), 'todo2.txt')
  File "testing.py", line 32, in save_list
    print>>f.write("\n".join(todolist))
TypeError: sequence item 0: expected string, tuple found

期待一个字符串,我如何更改它以原始格式打印元组?

2 个答案:

答案 0 :(得分:2)

该例外清楚地表明了您的问题:

  File "C:\University\CSSE1001\assignment 1\testing.py", line 21, in load_list
    task, date = line.rsplit(',', 1)
ValueError: need more than 1 value to unpack

您正在阅读的数据不包含逗号。因此,当您用逗号分割它时,您只会收到一个值,并且可以将其分配给元组。

请检查您的输入数据。您还可以添加以下行:

try:
  task, data = line.rsplit(',', 1)
except ValueError as e:
  print "Coultn't parse:", line
  raise e

显示哪一行是个问题。

答案 1 :(得分:0)

调用两个函数的工作代码:

def as_datetime(date_string):
    try:
        return datetime.datetime.strptime(date_string, DATE_FORMAT)
    except ValueError:
        # The date string was invalid
        return None

def as_date_string(date):
    return date.strftime(DATE_FORMAT)


def load_list(filename):
    new_list = []
    with open(filename, 'rU') as f:
        for line in f:
            task, date = line.rsplit(',', 1)
            try:
                # strip to remove any extra whitespace or new lines
                dates = as_datetime(date.strip())
            except ValueError:
                continue #go to next line
            new_list.append((dates,task))
    return new_list

def save_list(todolist, filename):
    with open(filename, 'w') as f:
        for date, task in todolist:
            dates = as_date_string(date)
            f.write("%s,%s\n" % (task, dates))

&#39; date&#39;,&#39; task&#39;在for循环中回到了前面。二手&#39;日期&#39;作为一个新的变量。