Reputation: 17
I'm trying to read a .txt file line by line with a while loop, split each line at a comma intersection, call a function to return the "date" side of each line to a list, then append the "task" side to the datetime in the list.
Example line in the .txt file: "tutorial signons,28/02/2014"
The result should look like: (datetime.datetime(2014, 2, 28, 0, 0), 'tutorial signons')
My code at the moment is returning this: ['t', 'u', 't', 'o', 'r', 'i', 'a', 'l', ' ', 's', 'i', 'g', 'n', 'o', 'n', 's', ',', '2', '8', '/', '0', '2', '/', '2', '0', '1', '4', '\n']
Datetime Function:
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 function:
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
Upvotes: 1
Views: 483
Reputation: 4674
Just a couple things:
rsplit
instead of split
. Using rsplit(',', 1)
will only split at the last comma."todo.txt"
should be filename
the way the function is written.with
for files where appropriate.The edited version looks like:
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
This returns a list of tuples. Which you could easily iterate through:
for date, task in load_list('todo.txt'):
print 'On ' + date.strftime(DATE_FORMAT) + ', do task: ' + task
Finally, I would normally suggest using the csv
module, since your file looks like a csv file. If task
will never have commas in it, then the csv.reader()
functionality can replace rsplit
.
Upvotes: 0
Reputation: 379
you have to capture line.split(',') in a variable. split doesn't alter the original variable.
Upvotes: 1