【问题标题】:Make glob directory variable使 glob 目录变量
【发布时间】:2018-05-16 17:59:01
【问题描述】:

我正在尝试编写一个 Python 脚本,用于在文件夹中搜索所有扩展名为 .txt 的文件。在手册中,我只看到它硬编码为glob.glob("hardcoded path")

如何将 glob 搜索模式的目录设为变量?具体来说:用户输入。

这是我尝试过的:

import glob

input_directory = input("Please specify input folder: ") 
txt_files = glob.glob(input_directory+"*.txt")
print(txt_files)

尽管提供了包含.txt 文件的正确目录,但脚本会打印一个空列表[ ]

【问题讨论】:

  • 你使用的是 windows、mac 还是 linux?
  • 您可能只是在输入搜索模式中缺少反斜杠(或正斜杠)
  • 你能显示print(input_directory+"*.txt")的输出吗?

标签: python python-3.x glob


【解决方案1】:

如果您不确定路径末尾是否包含分隔符(通常为'/''\'),您可以使用os.path.join 进行连接。这是一种比手动添加本地操作系统的路径分隔符更便携的方法,并且比编写条件以确定是否每次都需要更短:

import glob
import os

input_directory = input('Please specify input folder: ') 
txt_files = glob.glob(os.path.join(input_directory, '*.txt'))
print(txt_files)

【讨论】:

    【解决方案2】:

    对于 Python 3.4+,您可以为此使用 pathlib.Path.glob()

    import pathlib
    
    input_directory = pathlib.Path(input('Please specify input folder: '))
    if not input_directory.is_dir():
        # Input is invalid.  Bail or ask for a new input.
    for file in input_directory.glob('*.txt'):
        # Do something with file.
    

    is_dir() 和 glob 之间存在 time of check to time of use 竞争,不幸的是,这种竞争无法轻易避免,因为在这种情况下 glob() 只会返回一个空迭代器。在 Windows 上,甚至可能无法避免,因为您无法打开目录来获取文件描述符。在大多数情况下这可能没问题,但如果您的应用程序具有a different set of privileges from the end user 或来自其他对父目录具有写访问权限的应用程序,则可能会出现问题。此问题也适用于使用glob.glob() 的任何解决方案,具有相同的行为。

    最后,Path.glob() 返回一个迭代器,而不是一个列表。所以你需要循环遍历它,或者将它传递给list() 来实现它。

    【讨论】:

      猜你喜欢
      • 2014-06-02
      • 2017-07-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-11
      • 1970-01-01
      • 2020-02-27
      • 2019-12-13
      相关资源
      最近更新 更多