0

I'm trying to run a csv file in python.

Here is the code I'm having trouble with:

with open("\Home\myname\Downloads\my_file.csv") as file_handler:

Not sure if this is relevant, but my name starts with an M and the file name starts with an A.

When I try to run it, this is the error message I get:

FileNotFoundError: [Errno 2] No such file or directory: 
'\\Home\\myname\\Downloads\x07my_file.csv'

I tried replacing single backslashes with double, and I get:

FileNotFoundError: [Errno 2] No such file or directory: 
'\\Home\\myname\\Downloads\\my_file.csv'

Can anyone show me how to get it to be read as just one slash? (I apologize if this is a simple question, I'm not too familiar with coding.)

martineau
  • 119,623
  • 25
  • 170
  • 301
tghvkj
  • 13
  • 4
  • 1
    use this `r"\Home\myname\Downloads\my_file.csv"` – bigbounty Jul 13 '20 at 20:45
  • These days forward slashes work with python on windows. But when the error text itself says `'\\Home\\myname\\Downloads\\my_file.csv'` isn't found, those are properly escaped backslashes and its means that your "Downloads" directory doesn't have a "my_file.csv". Is it really there and spelled the same?! – tdelaney Jul 13 '20 at 20:48
  • If `'\\Home\\myname\\Downloads\\my_file.csv'` doesn't work, then you have the file path wrong, or you don't have access to it. – khelwood Jul 13 '20 at 20:48
  • @tdelaney yep that was the problem, thank you so much! – tghvkj Jul 13 '20 at 23:34

2 Answers2

1

You should do

with open(r"\Home\myname\Downloads\my_file.csv") as file_handler:

That r make python interpret the string as raw. This is pertinent because \ would otherwise be treated as a special character in python.

alternatively, seeing as you are using \\ which would be the equivalent of a regular \ in python, it is possible that my_file.csv does not exist.

Ariel A
  • 474
  • 4
  • 14
0

Use a raw string where Python treats backslashes as literal characters. See more info here.

with open(r"\Home\myname\Downloads\my_file.csv") as file_handler:
Balázs
  • 496
  • 3
  • 8