Search code examples
pythonpathfilepathos.pathpathlib

In Python Getting the folder wrong with pathlib ( \u2069 )


I can not make the following code work in my mac and I don't know why.

import os
from pathlib import Path   
list_file_name     = 'listoffiles.txt'
list_of_files_path = Path('Users⁩/jose⁩/CODE⁩/OPS')
list_file_with_path= os.path.join (list_of_files_path,list_file_name )
print(list_of_files_path)

result: Users⁩/jose⁩/CODE⁩/OPS/listoffiles.txt which seems to be ok

but when I go on in order to read the text file into a list:

lineList = [line.rstrip('\n') for line in open(list_file_with_path)]

I get: FileNotFoundError: [Errno 2] No such file or directory: 'Users\u2069/jose\u2069/CODE\u2069/OPS/listoffiles.txt'

I don't get how do I have to call the path in order to get it right.

Some help? what I am doing wrong?

NOTES: researching the problem in internet I found a couple of pages telling that the "old" way to work with paths in with os library, whereas the "new and good one" is pathlib from python 3.4. Is that so. Should I forget os?


Solution

  • The string in your sample code above has the Unicode characters directly entered in the string constant. I cut-n-pasted your code and see the result:

    from pathlib import Path   
    list_of_files_path = Path('Users⁩/jose⁩/CODE⁩/OPS')
    print(repr(list_of_files_path))
    

    Output:

    WindowsPath('Users\u2069/jose\u2069/CODE\u2069/OPS')
    

    My editor even displays them:

    editor with pictographs of control characters

    U+2069 is an invisible bidirectional text control character POP DIRECTIONAL ISOLATE. Maybe your editor was in a bidrectional text mode when it was typed? To fix, retype the string and make sure via repr() that there are no more control characters.