【发布时间】:2014-05-09 10:27:53
【问题描述】:
我正在尝试使用 while 循环逐行读取 .txt 文件,在逗号交点处拆分每一行,调用函数将每行的“日期”侧返回到列表,然后附加“任务”侧到列表中的日期时间。
.txt 文件中的示例行:“tutorial signons,28/02/2014”
结果应如下所示:(datetime.datetime(2014, 2, 28, 0, 0), 'tutorial signons')
我目前的代码正在返回: ['t','u','t','o','r','i','a','l','','s','i','g','n ', 'o', 'n', 's', ',', '2', '8', '/', '0', '2', '/', '2', '0', '1', '4', '\n']
日期时间函数:
def as_datetime(date_string):
try:
return datetime.datetime.strptime(date_string, DATE_FORMAT)
except ValueError:
# The date string was invalid
return None
load_list 函数:
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
【问题讨论】:
标签: python list split append tuples