How to read a single backslash?

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.)

Add Comment
2 Answer(s)

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.

Answered on July 16, 2020.
Add Comment

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: 
Answered on July 16, 2020.
Add Comment

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.