無法打開包含通配符的部分文件名的文件進行匹配。你需要做的是查看目錄中的所有文件,並選擇最匹配的文件。
簡單的例子:
import os
filename = "filename2017_" # known section
direc = r"directorypath"
matches = [ fname for fname in os.listdir(direc) if fname.startswith(filename) ]
print(matches)
但是,您可以使用glob
模塊(感謝bzimor)模式匹配您的文件。有關更多信息,請參閱glob docs。
import glob, os
# ? - represents any single character in the filename
# * - represents any number of characters in the filename
direc = r"directorypath"
pattern = 'filename2017-??-??-*.txt'
matches = glob.glob(os.path.join(direc, pattern))
print(matches)
先解決類似的是,你還回來的文件名列表供然後打開選擇。但是如果您需要的話,glob
模塊可以更準確地匹配您的文件。這一切都取決於你想要它有多緊張。
可能重複的[python插入變量字符串作爲文件名](http://stackoverflow.com/questions/14622314/python-inserting-variable-string-as-file-name) – bzimor
不完全。我的文件名字符串比那個更復雜。 – Dindsy