>>> import os
>>> os.chdir('c:/python27')
>>> os.listdir('c:')
['Tools', 'include', 'python.exe', 'libs', 'DLLs', 'Lib', 'NEWS.txt',
'w9xpopen.exe', 'Doc', 'pythonw.exe', 'LICENSE.txt', 'README.txt', 'tcl']
>>> os.listdir('c:/')
['users', 'Program Files', 'Python27', 'windows']
Why is the “/” after “c:” affecting the outcome? Is there a way to get os.listdir('c:') to return the contents of “c:/”?
This is not specific to Python, it’s a Windows question at heart.
In Windows
C:andC:\(or, alternativelyC:/) have quite different meanings:C:refers to the current directory on the driveC:C:\(andC:/) refers to the root directory of the driveC:While UNIX-like operating systems simply have a “current directory”, Windows has two separate notions:
So the current drive could be
D:, the current directory onC:could be\Windows(effectivelyC:\Windows) and the current directory onD:could be\Data(effectivelyD:\Data). In this scenario resolution would work like this:.would refer toD:\Data\would refer toD:\C:would refer toC:\WindowsC:\Foowould refer toC:\FooSo if you want to have information about a specific directory, you should always use a full path including both a drive and a directory, such as
C:\.