我试图通过用户输入获取目录路径,然后使用 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)