Chrystael
Chrystael

Reputation: 179

Saving list from python to text file in format

Say I have a txt file,

fantasy,12/03/2014
sci-fi,13/04/2014
history,03/04/2014

And I use the following code to convert it into a python list

def load_list(filename):
    my_file = open(filename, "rU")
    my_list = []
    for line in my_file:
        a,b = line.rstrip("\n").split(",")
        my_list.append((as_datetime(b),a))
    my_file.close()
    return my_list

which outputs [(datetime.datetime(2014, 3, 12, 0, 0), 'fantasy'), (datetime.datetime(2014, 4, 3, 0,
0), 'history'), (datetime.datetime(2014, 4, 12, 0, 0), 'sci-fi')].

I can assume that the list will be further modified (appended and removed) while being used. My question is, how can I implement a function to export the list as a txt file that followed the formatting of the original file?

Upvotes: 1

Views: 848

Answers (1)

alecxe
alecxe

Reputation: 473873

You can use csv module for reading and writing.

In order to follow the date format, use strptime() and strftime() (docs) from the datetime module.

Here's a complete example:

import csv
from datetime import datetime

FORMAT = '%d/%m/%Y'

def load_list(filename):
    my_list = []
    with open(filename, "rU") as f:
        reader = csv.reader(f)
        for line in reader:
            my_list.append([line[0], datetime.strptime(line[1], FORMAT)])
    return my_list


def save_list(filename, my_list):
    with open(filename, "w") as f:
        writer = csv.writer(f)
        for item in my_list:
            writer.writerow([item[0], item[1].strftime(FORMAT)])


my_list = load_list('input.txt')
save_list('output.txt', my_list)

It reads the data from input.txt and writes it to output.txt. After running the script, output.txt contains the same data as input.txt:

fantasy,12/03/2014
sci-fi,13/04/2014
history,03/04/2014

Hope that helps.

Upvotes: 1

Related Questions