我不擅长编写Python代码,我遇到了一些google无法帮我解决的问题。 我试图编写一个简单的目录列表工具,我似乎无法处理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\\是一个\\folder/'
它看起来像是逃走了。。。?
检查从原始输入()返回的值是否出现“\\”,并用“”替换它们。
相关问题 更多 >
编程相关推荐