简体   繁体   中英

.split() and .append information from .txt file as tuples to a new list

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

you have to capture line.split(',') in a variable. split doesn't alter the original variable.

Just a couple things:

  • Since your date is always on the right, and you may want commas in the command part, consider using rsplit instead of split . Using rsplit(',', 1) will only split at the last comma.
  • Capture the split output to two new variables.
  • Looks like "todo.txt" should be filename the way the function is written.
  • Use with for files where appropriate.
  • I'm not sure the purpose of some of the lower logic. I've written the code below to skip lines with no date or unreadabe date.

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 .

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM