【问题标题】:Opening file from path without knowing full file name (python)在不知道完整文件名的情况下从路径打开文件(python)
【发布时间】:2013-11-27 20:44:01
【问题描述】:

我正在尝试使用完整路径打开文件,但我不知道文件的完整名称,只是其中的一个唯一字符串。

i = identifier
doc = open(r'C:\my\path\*{0}*.txt'.format(i), 'r')

现在显然这不起作用,因为我正在尝试将通配符与原始字符串一起使用。过去我在尝试使用文件路径时遇到了很多麻烦 在它们之前没有'r',所以我不确定处理不完整文件名的最佳方法。我应该忘记原始字符串表示法并使用 '\\\\' 作为文件路径吗?

【问题讨论】:

  • docs.python.org/2/library/glob.html 是查找您不知道的文件名的最佳方式 - open 不适用于通配符。此外,在 DOS 路径名中使用反斜杠的最佳方法是使用 os.path.join 构建路径。
  • @PeterDeGlopper 如果我只做path=glob.glob(r'path/*identifier*.txt') 然后doc=open(path, 'r') 怎么办?
  • glob.glob 返回一个可能为空的列表,所以不能直接打开它的返回值。但是paths=glob.glob(...); if paths: doc = open(paths[0], 'r') 基本上是对的。 glob 似乎对您使用的文件分隔符表示宽容。

标签: python string filenames


【解决方案1】:

来自问题cmets:

import glob
import os

i = "identifier"
basePath = r"C:\my\path"

filePaths = glob.glob(os.path.join(basePath,'*{0}*.txt'.format(i)))

# Just open first ocurrence, if any
if filePaths:
    print "Found: ", filePaths[0]
    doc = open(filePaths[0], 'r')

【讨论】:

    猜你喜欢
    • 2015-07-08
    • 1970-01-01
    • 2021-09-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-17
    • 1970-01-01
    相关资源
    最近更新 更多