\ or / in Paths in Python

\ or / in Paths in Python

The character “\” is special in Python strings. You see \n, for example. So be careful about this character. Everything is OK in *nix, but… we have Windows! Well,sometimes Micro$oft  makes troubles. And when we wish to include the path to our file, we can see many “\” characters. What should we do? Well, we have two solutions.

You should use “/” not “\” for Windows. Surprised? You shouldn’t be. Python accepts that. So we write


rather than


Even Python in Windows understands that, so do not worry.

There’s other solution, too. If you are accustomed to Windows’ “\“, you can use “\\” that is just double the character “\“. So you can write in Python:


However, you should remember that this solution you can use only in the operating systems that use “\” as a separator in paths. You shouldn’t do that in Linux, Unix, etc. It works well in Windows.

Use “/” when your program is going to be portable among operating systems. You will avoid many troubles in the future. Using “\\” is recommended only in the situation when we are working in Windows, but we open our files by the program that doesn’t accept “/“. There is such software.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s