Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spaces in directory path python

I'm a noob at coding Python and I've run into something that no amount of Googling is helping me with. I'm trying to write a simple Directory listing tool and I cannot seem to deal with Spaces in the directory name in OSX. My code is as follows:

def listdir_nohidden(path):
    import os
    for f in os.listdir(path):
        if not f.startswith('.'):
            yield f

def MACListDirNoExt():
import os
MACu = PCu = os.environ['USER']
MACDIR = '/Users/'+MACu+'/Desktop//'
while True:
    PATH = raw_input("What is the PATH you would like to list?")
    if os.path.exists(PATH):
        break
    else:
        print "That PATH cannot be found or does not exist."
NAME = raw_input ("What would you like to name your file?")
DIR = listdir_nohidden(PATH)
DIR = [os.path.splitext(x)[0] for x in DIR]
f = open(''+MACDIR+NAME+'.txt', "w")
for file in DIR:
    f.write(str(file) + "\n")
f.close()
print "The file %s.txt has been written to your Desktop" % (NAME)
raw_input ("Press Enter to exit")

For ease of trouble shooting though I think this could essentially be boiled down to:

import os
PATH = raw_input("What is the PATH you would like to list")
os.listdir(PATH)

When supplying a directory path that contains spaces /Volumes/Disk/this is a folder it returns

"No such file or Directory: '/Volumes/Disk/this\\ is\\ a\\ folder/'

It looks like its escaping the escape...?

like image 204
dennis Avatar asked Apr 11 '16 18:04

dennis


2 Answers

Check the value returned from raw_input() for occurences of '\\' and replace them with ''.

a = a.replace('\\', '')
like image 64
trans1st0r Avatar answered Nov 14 '22 07:11

trans1st0r


I just ran into this, and I'm guessing that what I was hastily doing is also what you were trying. In a way, both @zwol and @trans1st0r are right.

Your boiled down program has nothing wrong with it. I believe that if you put in the input /Volumes/Disk/this is a folder, everything would work fine.

However, what you may have been doing (or at least, what I was doing) is dragging a folder from the Finder to the Terminal. When you drag to the Terminal, the OS automatically escapes spaces for you, so what ends up getting typed into the Terminal is /Volumes/Disk/this\ is\ a\ folder.

So either you can make sure that what you "type in" doesn't have those backslashes, or you can use @trans1st0r's suggestion as a way to support the dragging functionality, though the latter will cause issues in the edge case that your desired path actually has backslashes in it.

like image 43
leekaiinthesky Avatar answered Nov 14 '22 07:11

leekaiinthesky