1

I was wring a code to convert "\" in paths to "/" because "/" is what python uses.

However, when I was testing this super simple code, path like "C:\Users\Client\tests\doc_test_hard.docx" was converted to "C:/Users/Client/ ests/doc_test_hard.docx" because "/t" means 6 spaces.

I guess I will have same problem when my path has "\new_file" because \n means next line.

How do I tell python "/test" means "/test" instead of six spaces + "est"?

Kaizhen Ding
  • 33
  • 1
  • 5

2 Answers2

3

You can define the string as raw string, by prepending r to it, then the \ are not treated as escape characters. Example -

>>> s = r'C:\Users\Client\tests\doc_test_hard.docx'
>>> s
'C:\\Users\\Client\\tests\\doc_test_hard.docx'

After this, your replace should work -

>>> s.replace('\\','/')
'C:/Users/Client/tests/doc_test_hard.docx'

Though you actually may not need to do this, python should be able to handle the correct path separator for the os. If you are creating paths in your program, you should use os.path.join() , that would handle the path separators for you correctly.

Anand S Kumar
  • 88,551
  • 18
  • 188
  • 176
  • Thanks it works! However, it is difficult for me to use that in function, for example, if my function is change_path(path), I cannot really use rpath, even though path is supposed to be a string, how can I deal with it>? – Kaizhen Ding Aug 07 '15 at 19:30
  • If the path is taken as an input from somewhere or read from some file or some other source, then its already correctly escaped, do not worry about that. – Anand S Kumar Aug 07 '15 at 19:40
  • Get it. Thanks for your time – Kaizhen Ding Aug 07 '15 at 19:52
  • Man I am still stuck. I want to ask users(who does not know python and I do want to avoid teaching them) for a path, and the path would be new_path = raw_input("What is the path? ") and next my function will be dealing with that path. So I wonder what do I do with the parameter new_path (because I cannot simply do rnew_path) so that piece of string is correctly formatted? – Kaizhen Ding Aug 10 '15 at 12:29
  • Like I said, if you are getting the path through user input (like `raw_input()` ) it would be correctly formatted. No worries, try it out, are you facing any issue? If so, let me know , I can try to see what is going wrong. – Anand S Kumar Aug 10 '15 at 16:35
  • I dont know somehow my rawinput here does not give correct path. It was solved through this way.. The first answer http://stackoverflow.com/questions/12605090/how-to-prevent-automatic-escaping-of-special-characters-in-python – Kaizhen Ding Aug 11 '15 at 22:27
0

You can normalise path using os.path.normpath(). It can deal with \ and / and relative paths. And you don't have to change \ to / manually.

>>> p = os.path.normpath('C:\\directory/./file.ext')
>>> p
'C:\\directory\\file.ext'
>>> print p
C:\directory\file.ext
changhwan
  • 1,000
  • 8
  • 22