1

I am learning the os module of python, where I wrote the following code to try out the functions of the module.

Input:

os.getcwd()

Output:

'C:\\projects\\humming_bird'

Input:

os.listdir()

Output:

['.ipynb_checkpoints',
 'All_images',
 'hummingbirds',
 'Untitled.ipynb',
 'video_test']

Input:

os.listdir('C:\projects\humming_bird\hummingbirds\train\Rufous_female')

Output:

OSError                                   Traceback (most recent call last)
<ipython-input-23-fad4f5df47d8> in <module>
----> 1 os.listdir('hummingbirds\train\Rufous_female')

OSError: [WinError 123] The filename, directory name, or volume label syntax is incorrect: 'hummingbirds\train\\Rufous_female'

Despite the file is present at the given location, yet it's showing the error. Please help!

Tsyvarev
  • 60,011
  • 17
  • 110
  • 153
Samar Pratap Singh
  • 471
  • 1
  • 10
  • 29

3 Answers3

3

Well passing your path in usual manner isn't accept directly by python due to presence of Espace sequences like \n, \t etc. So you have to alter your path as below

os.listdir('C:\projects\humming_bird\hummingbirds\train\Rufous_female')

To modified os.listdir('C:\\projects\\humming_bird\\hummingbirds\\train\\Rufous_female') Adding extra backslash tells the python interpreter to take it as normal backslash rather than a escape sequence. Now in the above case If the file or directory will be available or not be restricted due to admin accessibility to that directory then it will not show any error.

However, if still the file or directory is there and path is entered same above with modification and if it shows error , then make sure to run the script in adminstrator mode in the terminal or ide. For this simply run your ide or terminal as administrator

Hack Try
  • 471
  • 4
  • 17
1

In python, the backslash is used as an ignore symbol. So after each backslash add another backslash

Zachary
  • 532
  • 3
  • 12
1

You should try this way:

os.listdir("C:\\projects\\humming_bird\\hummingbirds\\train\\Rufous_female")