【问题标题】:What is the proper way to take a directory input with spaces from a user? (Python3)从用户那里获取带有空格的目录输入的正确方法是什么? (Python3)
【发布时间】: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


【解决方案1】:

考虑使用shlex.quote。

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

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

【讨论】:

  • 你不应该使用shlex.quote()。直接传递目录路径即可:os.walk(fileDirectory)。有没有空格没关系。
【解决方案2】:

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

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()):
    ...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-05-09
    • 2019-07-20
    • 1970-01-01
    • 2019-04-11
    • 2018-08-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多