目录路径python中的空格 [英] Spaces in directory path python

查看:193
本文介绍了目录路径python中的空格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Python的新手,但是遇到了一些Google搜索无法帮助我的事情.我正在尝试编写一个简单的目录列表工具,但似乎无法在OSX中处理目录名称中的空格.我的代码如下:

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)

在提供包含空格/Volumes/Disk/这是它返回的文件夹的目录路径时

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

没有此类文件或目录:'/Volumes/Disk/this \\ is \\ a \\ folder/'

似乎逃脱了……?

推荐答案

检查从raw_input()返回的值是否出现'\\',并用''替换它们.

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

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

这篇关于目录路径python中的空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆