Nick-H
Nick-H

Reputation: 388

Why don't backslashes work when using os.path.exists() in python but forward slashes do work?

I am learning how to use the OS module in python and when i copy the file path from the file explorer directly into python like follows:

os.path.exists('C:\Users\nheme\Documents\Classes\ME 4720 TSL\Flowmeter 
Lab\example.docx')
Out[43]: False

The output is False, which doesn't make sense because the file and path definitely do exist. Then when i replace the backslashes with forward slashes as follows:

os.path.exists('C://Users//nheme//Documents//Classes//ME 4720 TSL//Flowmeter 
Lab/example.docx')
Out[42]: True

It returns True. Can someone please explain why this is happening?

Upvotes: 0

Views: 1087

Answers (2)

user8747784
user8747784

Reputation:

When you use single backslashes in paths it doesn't work. use C:\\Users\\nheme\\Documents\\Classes\\ME 4720 TSL\\FlowmeterLab\\example.docx instead.

Upvotes: 0

Charlie Martin
Charlie Martin

Reputation: 112356

Because backslash is an escape character in Python strings.

Here's what happens when you just try to print that string in Python 2

>>> s = 'C:\Users\nheme\Documents\Classes\ME 4720 TSL\FlowmeterLab\example.docx'
>>> print s
C:\Users
heme\Documents\Classes\ME 4720 TSL\FlowmeterLab\example.docx
>>>

Python has interpreted the \n as the escape code for a newline.

There are ways around that, eg, using a raw string

>>> s = r'C:\Users\nheme\Documents\Classes\ME 4720 TSL\FlowmeterLab\example.docx'
>>> print s
C:\Users\nheme\Documents\Classes\ME 4720 TSL\FlowmeterLab\example.docx
>>>

or you could change all the \ to \\

>>> s = 'C:\\Users\\nheme\\Documents\\Classes\\ME 4720 TSL\\FlowmeterLab\\example.docx'
>>> print s
C:\Users\nheme\Documents\Classes\ME 4720 TSL\FlowmeterLab\example.docx

Upvotes: 1

Related Questions