I am trying to write a function which saves a list created by reading a .txt file back in its original format.
Code which generates the list in this format:
(datetime.datetime(2014, 2, 28, 0, 0), 'tutorial signons')
From the format of the .txt file:
"tutorial signons,28/02/2014"
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
Function attempting to save "todolist" as a new "filename":
def save_list(todolist, filename):
with open('todo.txt', 'w') as f:
print>>f.write("\n".join(todolist))
Using the desired input:
>>>save_list(load_list('todo.txt'), 'todo2.txt')
Returns this error:
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
It is expecting a string, how would I change this to print the tuple in the original format?
The exception clearly identifies your problem:
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
The data you are reading doesn't contain a comma. Hence, when you split it by a comma, you receive only one value and this can be assigned to a tuple.
Please examine your input data. You can also add following line:
try:
task, data = line.rsplit(',', 1)
except ValueError as e:
print "Coultn't parse:", line
raise e
to display what line is a problem.
Working code calling two functions:
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' were back to front in the for loop. Used 'dates' as a new variable.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.