Python .split()和.append.txt文件中的信息作为元组添加到新列表中

Python .split()和.append.txt文件中的信息作为元组添加到新列表中,python,list,split,append,tuples,Python,List,Split,Append,Tuples,我试图用while循环逐行读取一个.txt文件,在逗号交叉处拆分每一行,调用函数将每一行的“日期”端返回到列表中,然后将“任务”端附加到列表中的日期时间 .txt文件中的示例行:“教程签名,2014年2月28日” 结果应该如下所示:(datetime.datetime(2014,2,28,0,0),‘教程签名’) 目前我的代码返回以下内容: [t',u',t',o',r',i',a',l',s',i',g',n',o',n',s',n',s',n',s',n',s',n',s',n',s',s'

我试图用while循环逐行读取一个.txt文件,在逗号交叉处拆分每一行,调用函数将每一行的“日期”端返回到列表中,然后将“任务”端附加到列表中的日期时间

.txt文件中的示例行:“教程签名,2014年2月28日”

结果应该如下所示:(datetime.datetime(2014,2,28,0,0),‘教程签名’)

目前我的代码返回以下内容: [t',u',t',o',r',i',a',l',s',i',g',n',o',n',s',n',s',n',s',n',s',n',s',n',s',s',s',s',s',s',s',s',s',s',n',s',s',s',n',s',s',s'

日期时间函数:

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 = []
    f = open("todo.txt", 'rU')
    while 1:
        line = f.readline()
        line.split(',')
        task = line[1:0]
        datetime = as_datetime(line)
        if not line:
            break
        for datetime in line:
            new_list.append(datetime)
        for task in line:
            new_list.append(task)
        return new_list

您必须捕获变量中的line.split(',')。split不会改变原始变量。

只需做几件事:

    <> LI>因为您的日期总是在右边,并且您可能需要命令部分中的逗号,请考虑使用<代码> R拆分< /代码>而不是<代码>分割< /代码>。使用
    rsplit(',',1)
    将仅在最后一个逗号处拆分
  • 将拆分输出捕获为两个新变量
  • 看起来
    “todo.txt”
    应该是函数的编写方式
  • 在适当的情况下,将
    一起用于文件
  • 我不确定一些低级逻辑的目的。我写了下面的代码来跳过没有日期或无法读取日期的行
编辑的版本如下所示:

DATE_FORMAT = '%d/%m/%Y'
import datetime
def load_list(filename):
    new_list = []
    with open(filename, 'rU') as f:
        for line in f:
            task, date = line.rsplit(',', 1)
            try:
                # strip removes any extra white space / newlines
                date = datetime.datetime.strptime(date.strip(), DATE_FORMAT)
            except ValueError:
                continue # go to next line
            new_list.append((date, task))
    return new_list
这将返回一个元组列表。您可以很容易地对其进行迭代:

for date, task in load_list('todo.txt'):
    print 'On ' + date.strftime(DATE_FORMAT) + ', do task: ' + task

最后,我通常建议使用
csv
模块,因为您的文件看起来像一个csv文件。如果
task
中永远不会有逗号,那么
csv.reader()
功能可以替换
rsplit

如果变量看起来像:task=line.split(','),我如何指定要从拆分的哪一侧获取值?我是否会使用task=line.split((',')[0:1])?非常感谢您的建议,这里的“with”在打开文件时看起来非常有用。这段代码工作得很好,不需要调用as_datetime函数。该文件只包含逗号,因此如果更稳定的话,我可能会尝试使用csv.reader()进行拆分。