1

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?

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

6 Comments

One more question - instead of the from datetime import datetime that you are using, I have been given seperate functions to convert dates to and from datetime. the function that converts the string into datetime works fine ( my_list.append([as_datetime(line[1]), line[0]]), but converting the datetime into a string in the save_list function is giving an error. The function for converting datetime to string is def as_date_string(date): return date.strftime(DATE_FORMAT) is not working when I call it like this writer.writerow([item[0], as_date_string(item[1])])
@Chrystael ok, what error are you getting? What is the value of a datetime at the point? What is DATE_FORMAT?
This is the entire error: Traceback (most recent call last): File "<pyshell#12>", line 1, in <module> save_list("outputtest.txt", my_list) File "C:\Users\anon\Desktop\Python 1\assign1test.py", line 53, in save_list writer.writerow([item[0], as_date_string(item[1])]) File "C:\Users\anon\Desktop\Python 1\assign1test.py", line 30, in as_date_string return date.strftime(DATE_FORMAT) AttributeError: 'str' object has no attribute 'strftime' DATE_FORMAT is simply FORMAT from your solution.
@Chrystael the error says that date is a string at the point, not datetime. Cannot say more without seeing the code you are using.
The difference being that instead of using from datetime import datetime, I am using import datetime and the seperate functions def as_datetime(date_string): try: return datetime.datetime.strptime(date_string, DATE_FORMAT) and def as_date_string(date): return date.strftime(DATE_FORMAT) to change the date between a string and a datetime.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.