【发布时间】:2014-05-19 00:10:59
【问题描述】:
我正在尝试通过用户输入获取目录路径,然后使用 os.walk() 遍历目录。如果我尝试输入带有空格的路径(即“用户/用户/带有空格/文件夹/的文件夹”),我的程序就会中断。
从用户那里获取带有空格的目录输入的正确方法是什么? (Python3)
我的代码如下所示:
fileDirectory = input("Enter in a path to import")
try:
for root, dirs, files in os.walk(shlex.quote(fileDirectory)):
for f in files:
print(f)
fileLocation = os.path.join(root, f) #Saves the path of the file
print(fileLocation)
size = os.path.getsize(fileLocation) #Gets the file size
print(size)
filePath, fileExt = os.path.splitext(fileLocation) #splits path and extension, defines two variables
print(fileExt)
print(filePath)
except Exception as msg:
print(msg)
【问题讨论】:
-
它究竟是如何以及在哪里中断的?我刚刚运行了一个测试,我打印出
rootdirs和files,并没有在 Python 3.4 上发现任何错误。 -
程序在没有空格的情况下运行,但在目录中有空格的地方,它就结束了。我尝试使用“try/except”子句处理错误,但没有为“异常”打印任何内容。抱歉,我没有更多信息。
-
您能描述一下您的
some code的用途吗? -
代码的一部分用于打印每个文件的属性。这里是一个例子:'for f in files: print(f) fileLocation = os.path.join(root, f) #保存文件的路径 print(fileLocation) size = os.path.getsize(fileLocation) #Gets文件大小 print(size) filePath, fileExt = os.path.splitext(fileLocation) #分割路径和扩展名,定义两个变量 print(fileExt) print(filePath)'
-
请更新您的问题。所以 cmets 不支持换行符!
标签: python input python-3.4 os.walk