我是 Python 编码新手,但我遇到了一些谷歌搜索也无法帮助我解决的问题。
我正在尝试编写一个简单的目录列表工具,但我似乎无法处理 OSX 中目录名称中的空格。
我的代码如下:
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")
为了便于故障排除,我认为这基本上可以归结为:
import os
PATH = raw_input("What is the PATH you would like to list")
os.listdir(PATH)
当提供包含空格 /Volumes/Disk/this 的目录路径时,它返回一个文件夹
“没有这样的文件或目录:'/Volumes/Disk/this\\ is\\ a\\文件夹/'
看起来像是在逃亡……?
检查 raw_input() 返回的值中是否出现 '\\' 并将其替换为 ''。
a = a.replace('\\', '')
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)