0

I have a list which looks like this:

dates_to_process = ['20201203', '20201201', '20201203']

This list changes every now and then but I try to write those dates into my logfile. I prefer it to be in chronoclical order if thats possible.

This is my code:

with open(log_location, 'a') as output:
    if output.tell() == 0:      
        output.write('Date last Run\n')
    output.write(dates_to_process + '\n')

This is my wished outcome if I open the log_file:

Date last Run
20201201
20201202
20201203

This is whay I get now when I run the code:

TypeError: can only concatenate list (not "str") to list
TangerCity
  • 775
  • 2
  • 7
  • 13
  • 1
    You can convert the list to a String like this `"\n".join(dates_to_process)`, before writing to the file. As it is, you are trying to concatenate `dates_to_process`, a list with a String `\n`. – thefourtheye Dec 09 '20 at 14:33
  • does this answer your question? :https://stackoverflow.com/questions/899103/writing-a-list-to-a-file-with-python – JacksonPro Dec 09 '20 at 14:34
  • I feel that it's a pretty bad dupe as the question is about serialization/being able to get the original list back, whereas this is about writing a list to a file in a specific format. – Aplet123 Dec 09 '20 at 14:35
  • Perhaps the dup target changed? The current link doesn't talk about serialization. Also, OP, the error you're getting is because `dates_to_process` is a list and `'\n'` is a string. You cant concatenate them. As suggested by the comments in the dup, try `thefile.write('\n'.join(thelist))` or loop over the list, writing each line individually. – code11 Dec 09 '20 at 14:40
  • the answer of @thefourtheye did the job actually but its not yet in chronoloical order is it? – TangerCity Dec 09 '20 at 14:42
  • @TangerCity If the data is going to be in this format, you can throw in a `sorted` after converting the list items to numbers with `int`. – thefourtheye Dec 09 '20 at 14:45

0 Answers0