我正在尝试使用 while 循环逐行读取 .txt 文件,在逗号交叉处分割每一行,调用一个函数将每行的“日期”一侧返回到列表,然后 append “任务”一侧添加到列表中的日期时间。
.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
最佳答案
你必须在变量中捕获 line.split(',') 。 split 不会改变原始变量。
关于python - .split() 和 .append 来自 .txt 文件的信息作为元组到新列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22738601/