-3

I'm using this command in my code

with open(r"files\data.txt", "r") as file:

and I'm getting this error

No such file or directory: 'files\\data.txt'

I've also tried using \ as I've seen this mentioned as a solution but it still doesn't work

with open("files\\data.txt", "r") as file:

comes out as

No such file or directory: 'files\\data.txt'

I feel like I'm following exactly as this site recommends https://www.geeksforgeeks.org/python-raw-strings/ but it still doesn't work. Does my raw string not work properly? I'm using VS Code if that helps.

Risly
  • 1
  • fun fact: Windows supports `/` in paths just fine. It's *always* supported them just fine. The only time things get funky is if your path has spaces in it. However, remember to use correct paths. Relative paths start with `./` or `../`. – Mike 'Pomax' Kamermans Aug 19 '23 at 00:23
  • 4
    The filename is **printed** with double backslashes because that's just how strings are printed in python. The real string only has one backslash. The actual problem is that the file **isn't there**, just as the error says. – John Gordon Aug 19 '23 at 00:26
  • 2
    The root cause of this error is that you're expecting `files` to be in the **current directory**, but it isn't. – John Gordon Aug 19 '23 at 00:29
  • You can use this code to display the actual current directory `import os; print(os.getcwd())` – John Gordon Aug 19 '23 at 00:31
  • thank you both. yeah the relative path was so wrong i've got the right path now and it's working. and i'm gonna use forward slashes too now – Risly Aug 19 '23 at 00:31

0 Answers0