使 glob 目录变量

Make glob directory variable

我正在尝试编写一个 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 文件提供了正确的目录,但脚本会打印一个空列表 [ ]

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

import glob
import os

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

对于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.

有一个 time of check to time of use race between the is_dir() and the glob, which unfortunately cannot be easily avoided because glob() just returns an empty iterator in that case. On Windows, it may not even be possible to avoid because you cannot open directories to get a file descriptor. This is probably fine in most cases, but could be a problem if your application has a different set of privileges from the end user 或来自其他对父目录具有写入权限的应用程序。此问题也适用于使用 glob.glob() 的任何解决方案,它们具有相同的行为。

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