pythondatecsvwriterstring-iteration

how to prevent the writerow method to iterate through a string


I want to write a string to a csv using writerow but the result I'm getting is not what i want

def date_csv():

    date_str = pd.Timestamp.today().strftime('%d-%m-%Y')
    print(date_str)   ### output: 16-04-2022
    with open("Alert_date.csv", "a", newline="") as file:
        writer_object = writer(file)
        writer_object.writerow(date_str)

csv file result:

1,6,-,0,4,-,2,0,2,2

what i want:

16-04-2022

Solution

  • writerow writes an iterable in a single line, with each item separated by the separator.

    A string is an iterable, so the result of writerow('abc') is a,b,c. If you want to write a string as a single element you can put it inside another iterable, like a list: writerow(['abc']) -> abc