【发布时间】: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。