0

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

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.

enerneo
  • 43
  • 6

2 Answers2

1

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

John Gordon
  • 29,573
  • 7
  • 33
  • 58
1

You can use raw strings r'tech\tech_part.txt' to ignore backslash escapes (except some edge conditions such as a backslash as the last character in the string). But these days, you can use forward slashes with Windows, so just do that.

For all of the string rules, see String and Bytes literals

tdelaney
  • 73,364
  • 6
  • 83
  • 116