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']
The double backslash is there because you’re calling
printon a list, which prints thereprof the list’s elements:repris also giving you the quotes around the strings. The idea is that the output ofrepr(for simple types likestr) can be fed back to the Python interpreter directly. To print without quotes and with single backslashes, print the elements separately:Use this form when communicating with the outside world.
Btw., for walking directory hierarchies, use
os.walkand for constructing paths, useos.path.join.