Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to read a file with special characters present in its path?

What is done when encountered with special letters in file path, when trying to access it?

To open a file, we need the specific path to the location where it lies. But in cases where the file path itself contains some special characters, like t, just after \, it shows error:

OSError: [Errno 22] Invalid argument: 'tech\tech_part.txt'.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

How to deal with it?

I am writing this in python and the above error results at this line:

f = open('tech\tech_part.txt', 'r')

Please note that I have already searched over the web and I found this link and some other (related) queries either not answered (or, done satisfactorily). Any help would be welcomed. If I have missed anything that is already available, please mention. Thanks.

>Solution :

Use a raw string, by putting r immediately before the string.

f = open(r'tech\tech_part.txt', 'r')

This forces Python to not apply the usual rules of backslash escapes, and so it treats \t as simply "backslash followed by t", instead of "tab".

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading