0

I'm writing a Python script on a Windows OS that needs to find a specific file in the Downloads directory and then automatically send an email with that specific file attached. The issue I'm running into is when I try to attach the file using the file path.

I run into the SyntaxError: (unicode error) because of the single backslash in the file path file_path = "C:\Users\....

Obviously, I can just add another backslash manually to make it read the file properly like so file_path = "C:\\Users\...

But if I plan on running this script every day, I don't want to manually add that second backslash in every time.

I've tried the following with no luck.

First attempt:

import os

file_path = "C:\Users\mmacwan\Downloads\...
file_path.replace(os.sep, '//')

Second attempt:

try:
    file_path = "C:\Users\mmacwan\Downloads\...
except SyntaxError:
     print('Bypassed SyntaxError')

Third attempt:

from path lib import Path

file_path = os.path.normpath("C:\Users\mmacwan\Downloads\...)
file_path.replace(os.sep,'//')
martineau
  • 119,623
  • 25
  • 170
  • 301
  • 1
    `r"C:\Users\mmacwan\Downloads\..."` – khelwood Apr 14 '22 at 17:43
  • Prefix the string with an `r` — see *raw strings* in [String and Bytes literals](https://docs.python.org/3/reference/lexical_analysis.html#string-and-bytes-literals) section of the documentation. Also note that you *can* use forward slashes on Windows computers and avoid the whole issue (as well as be more portable). Another option would be to use the [`pathlib`](https://docs.python.org/3/py-modindex.html#cap-p) module (and forward slashes). – martineau Apr 14 '22 at 19:17

0 Answers0