gpt4 book ai didi

python - 在不知道完整文件名的情况下从路径打开文件(python)

转载 作者:行者123 更新时间:2023-12-01 05:31:14 25 4
gpt4 key购买 nike

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

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

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

最佳答案

来自问题评论:

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')

关于python - 在不知道完整文件名的情况下从路径打开文件(python),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20252722/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com