nairware
nairware

Reputation: 3190

Python Filepaths

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

Answers (2)

Fred Foo
Fred Foo

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

Geospatial_D
Geospatial_D

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]

  1. thisDir is the string of the directory that the walk is examining
  2. listDirs is a list of the string of Directory names inside of thisDir
  3. listFiles is a list of the strings of file names inside thisDir

You can iterate or process the returned list, and pluck out whatever you need.

Upvotes: 0

Related Questions