I want to concatenate timestamp to individual list elements to create a txt or csv file. Here's the code I tried which is concatenating the timestamp to the last element only. So I am doing it wrong. Appreciate any help. Thanks
The expected output is
BSTG,2022-01-13 22:09:07
XTLB,2022-01-13 22:09:07
SERA,2022-01-13 22:09:07
SIDU,2022-01-13 22:09:07
RPID,2022-01-13 22:09:07
BBLN,2022-01-13 22:09:07
SGLY,2022-01-13 22:09:07
DAVE,2022-01-13 22:09:07
GMVD,2022-01-13 22:09:07
BBIG,2022-01-13 22:09:07
# Code Begin
from datetime import datetime
current_results = ['BSTG,XTLB,SERA,SIDU,RPID,BBLN,SGLY,DAVE,GMVD,BBIG']
now = datetime.now()
print(current_results)
for elem in current_results:
print(str(elem)+str(now))
#Code End
There are two problems here that I notice:
current_results = ['BSTG,XTLB,SERA,SIDU,RPID,BBLN,SGLY,DAVE,GMVD,BBIG']
is a list with just one str
element.
Instead you may want to use:
current_results = ['BSTG', 'XTLB', 'SERA', 'SIDU' , 'RPID', 'BBLN', 'SGLY', 'DAVE', 'GMVD', 'BBIG']
When you concatenate results the comma is missing. You may want to use f-strings https://www.python.org/dev/peps/pep-0498/ to format the CSV output easily.
print(f"{elem},{now}")
There are csv specific libraries, e.g. built-in csv
but for such a simple case they could be an overkill.