Problem with character '\ n' when interpreting a date

0

Dear, I have a code to change dates of type string in a text file to a list of dates of type datetime :

import datetime as dt
import workdays
Holidays = open("C:\holidays.txt").readlines()
print (Holidays)

dates_list = [dt.datetime.strptime(date, '"%Y-%m-%d"').date() for date in 
Holidays]
print(dates_list)
al leerlas con la funcion open("archivo.txt")

I have the following error: ValueError: time data '2017-09-18\n' does not match format '"%Y-%m-%d"' . Apparently when reading the text a character \n is generated at the end of the date and that's why I can not transform strings to date. The text file is UTF-8 without BOM.

greetings

    
asked by Richie 22.11.2017 в 16:59
source

1 answer

0

The \n is the end-of-line character of any text file. readlines() includes it in the items corresponding to each line so you should remove it, using for example rstrip() , like this:

dates_list = [dt.datetime.strptime(date.rstrip(), '"%Y-%m-%d"').date() for date in 
Holidays]

On the other hand I remind you that you must close the files you have opened, with close() or failing that and better still use a contextmanager that automatically closes the file once we no longer need it:

with open("archivo.txt", mode='r', encoding='utf-8') as f:
    Holidays = f.readlines()
    
answered by 22.11.2017 / 17:31
source