1

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

2 回答 2

0

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

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()):
    ...
于 2014-08-01T13:22:11.690 回答
0

考虑使用shlex.quote

在这种情况下,您会想要:

for root, dirs, files in os.walk(shlex.quote(fileDirectory)):
    #some code...
于 2014-05-19T00:26:09.493 回答