Saving list from python to text file in format -


say have txt file,

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

and use following code convert python list

def load_list(filename):     my_file = open(filename, "ru")     my_list = []     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 list further modified (appended , removed) while being used. question is, how can implement function export list txt file followed formatting of original file?

you can use csv module reading , writing.

in order follow date format, use strptime() , strftime() (docs) datetime module.

here's complete example:

import csv datetime import datetime  format = '%d/%m/%y'  def load_list(filename):     my_list = []     open(filename, "ru") f:         reader = csv.reader(f)         line in reader:             my_list.append([line[0], datetime.strptime(line[1], format)])     return my_list   def save_list(filename, my_list):     open(filename, "w") f:         writer = csv.writer(f)         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 data input.txt , writes output.txt. after running script, output.txt contains same data input.txt:

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

hope helps.


Comments

Popular posts from this blog

PHPMotion implementation - URL based videos (Hosted on separate location) -

javascript - Using Windows Media Player as video fallback for video tag -

c# - Unity IoC Lifetime per HttpRequest for UserStore -