【问题标题】:Making a function to save a list to a .txt file制作一个将列表保存到 .txt 文件的函数
【发布时间】:2014-03-31 14:48:19
【问题描述】:

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

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

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

从.txt文件的格式来看:

“教程签到,2014 年 2 月 28 日”

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

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

【问题讨论】:

  • 我达到了预期的结果,使用:file('todo2.txt','w').write(file('todo.txt').read().encode('utf-8' ) ) 但是把它变成一个函数是困难的
  • 文件中可能有空行。如果一行为空 (if not line),您可以使用 continue

标签: python list file function


【解决方案1】:

异常清楚地表明了您的问题:

  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

显示哪一行有问题。

【讨论】:

  • 你是对的,我的输入数据被保存了,只是“todo.txt”试图创建函数。我本可以有一个工作功能,只是没有阅读它的意思..
【解决方案2】:

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

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))

'date', 'task' 在 for 循环中回到前面。使用“日期”作为新变量。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-05
    • 1970-01-01
    相关资源
    最近更新 更多