I am trying to pass a variable file location be emailed via the my SQL server. If i am using some other string it will work fine but this is the error I am getting.
pyodbc.ProgrammingError: ('42000', '[42000] [Microsoft][ODBC SQL Server Driver][SQL Server]Attachment file C:\\Users\\ME\\Desktop\\Queries\\Fail w email\\PythonEmail\\ErrorList.txt is invalid. (22051) (SQLExecDirectW)')
Saying is can't handle '\' And it is driving me crazy. I've tried triple quote, triple double quotes, r"string", but nothing seems to work.
CODE:
import sys
import os
import pyodbc
con = pyodbc.connect('Trusted_Connection=yes', driver = '{SQL Server}',server = 'SERVER', database = 'DATABASE')
cur = con.cursor()
f = open('ErrorList.txt','w')
f.write("('Station','Sequence','Script','Measurement','Fail Count')"+'\n')
f.close()
print(os.path.abspath("ErrorList.txt"))
pathtofilename = r'C:\Users\ME\Desktop\Queries\Fail w email\PythonEmail\ErrorList.txt'
sendEmail = ("EXEC msdb.dbo.sp_send_dbmail "
"@body_format = 'TEXT', "
"@recipients = 'reci@reci', "
"@from_address = 'from@from' ,"
"@reply_to = 'reply@reply', "
"@subject = 'Test Python', "
" @file_attachments = '" + os.path.abspath('ErrorList.txt') + "', "
"@body = 'No Message with commit attach 2'")
cur.execute(sendEmail)
con.commit()
cur.close()
con.close()
os.remove("ErrorList.txt")