Reputation: 3190
I am trying to build a simple script which must be able to navigate through directories, sub-directories, and sub-sub-directories, and I have never done it before.
Why does this code generate the output that it does--with the double-backslash? Also, what should my code be doing, given my objectives?
I believe my objective is to maintain the single backslash, but I am unsure. All I know is I will be bouncing between different levels within the same directory--into sub-directories and sub-sub-directories. Trying to work through the program further, I believe I am running into errors by trying to look for files with filepaths that contain double backslashes.
import os, shutil, time
mdir = 'C:\\Users\Dev\Desktop\Python_Test'
dirlist = [(mdir + '\\' + i) for i in os.listdir(mdir) if os.path.isdir(os.path.join(mdir, i))]
print dirlist
Output:
['C:\\Users\\Dev\\Desktop\\Python_Test\\Dir 1',
'C:\\Users\\Dev\\Desktop\\Python_Test\\Dir 2']
Upvotes: 1
Views: 375
Reputation: 363858
The double backslash is there because you're calling print
on a list, which prints the repr
of the list's elements:
>>> l = ['C:\\Users\\Dev\\Desktop\\Python_Test\\Dir 1',
... 'C:\\Users\\Dev\\Desktop\\Python_Test\\Dir 2']
>>> for x in l:
... print(repr(x))
...
'C:\\Users\\Dev\\Desktop\\Python_Test\\Dir 1'
'C:\\Users\\Dev\\Desktop\\Python_Test\\Dir 2'
repr
is also giving you the quotes around the strings. The idea is that the output of repr
(for simple types like str
) can be fed back to the Python interpreter directly. To print without quotes and with single backslashes, print the elements separately:
>>> for x in l:
... print(x)
...
C:\Users\Dev\Desktop\Python_Test\Dir 1
C:\Users\Dev\Desktop\Python_Test\Dir 2
Use this form when communicating with the outside world.
Btw., for walking directory hierarchies, use os.walk
and for constructing paths, use os.path.join
.
Upvotes: 4
Reputation: 1
Use the os.walk intrinsic. It's great!
>>> import os
>>> os.walk('.')
<generator object walk at 0x163891E8>
>>> listWalk = []
>>> for items in os.walk('.'):
... listWalk.append(items)
...
>>> listWalk
listWalk will now contain a list of 3-part items: [thisDir, listDirs, listFiles]
You can iterate or process the returned list, and pluck out whatever you need.
Upvotes: 0