How can i handle filepath while has spaces followed with hyphen

Hi All,

I need help to read the file path which is as below:
file = os.listdir(“C:/Users/username/OneDrive - Company Name/Documents/Project Name/projectid/projectfolder/”)

In the above example when i try to access this path, i am getting exception as below : [WinError 3] The system cannot find the path specified:
C:/Users/username/OneDrive - Company Name/Documents/Project Name/projectid/projectfolder/"

As the "OneDrive " is been added in our company systems , i am unable to access previous paths which were not with “OneDrive”

Ex: C:/Users/username/Documents/Project Name/projectid/projectfolder/ path was accessible earlier but when one drive is been introduced, now i am not able to read the filepath completely from os.listdir to read the path present with OneDrive - Company Name

Can any one please help me to resolve this issue for windows?

Hello!

You should be able to if you add the @:

file = os.listdir(@"Path to Folder")

Hi There,
Thanks for your prompt reply.
can you please let me know if i have define the path outside os.listdir(), then how the path should be given.

ex:
path = ‘C:/Users/username/OneDrive - Company Name/Documents/Project Name/projectid/projectfolder/’

Could you please let me know?

Thanks,
PR

Adding one more Example:

Ex 2:
path = ‘C:/Users/username/OneDrive - Company Name/Documents’/
project1 = os.listdir(path + 'Project Name1/projectid/projectfolder/’)
project2 = os.listdir(path + 'Project Name2/projectid/projectfolder/’)

how can i define this path when it file path has spaces and hyphen like - OneDrive - Company Name and Project Name2 space between Project and Name??

It doesn’t matter if the path has hyphens, however, if it has \ it does: backslashes need to be escaped, that’s what the @ does.

When using a variable, simply use the @ in the assignment of the variable:

path = @"C:/Users/username/OneDrive - Company Name/Documents/"

Now that I read your first post again, does the path that fails actually exist? That path shouldn’t be a problem (if it had backslashes, it would). If you’re running the code on your computer, make sure that the path exists.

Thanks a lot @skaparate . I understood the issue and have fixed it with using @
Issue got resolved.

1 Like