Spaces in directory path python

橙三吉。 提交于 2019-12-12 14:34:08

问题


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...?


回答1:


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

a = a.replace('\\', '')



回答2:


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.



来源:https://stackoverflow.com/questions/36555950/spaces-in-directory-path-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!