从用户处获取带有空格的目录输入的正确方法是什么?(Python3)



我试图通过用户输入获取目录路径,然后使用os.walk()遍历目录。我的程序中断,如果我试图输入一个路径与空格(即。"Users/User/Folder with space/Folder/").

从用户处获取带有空格的目录输入的正确方法是什么?(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)

考虑使用shlex.quote。

在这种情况下,您需要:

for root, dirs, files in os.walk(shlex.quote(fileDirectory)):
    #some code...

创建一个单独的函数,返回一个有效的目录:

import os
def get_directory_from_user(prompt='Input a directory path'):
    while True:
        path = input(prompt)
        if os.path.isdir(path):
            return path
        print('%r is not a directory. Try again.' % path)

path是否有空格无关。将其传递给os.walk(),如下所示:

for dirpath, dirnames, files in os.walk(get_directory_from_user()):
    ...

相关内容

最新更新