所以,我希望我正确理解你,如果我这应该有所帮助。
import fnmatch
import os
def walk_directories(self, Dir, pattern):
root = Dir
for root, directories, files in os.walk(Dir):
for basename in files:
if fnmatch.fnmatch(basename, pattern):
_file_path = os.path.join(root, basename)
return _file_path
这是一个不同的目的而作出,但它应该满足您的需求,以及,我得到这个要找到包含在包含在单个根目录中“未知”的子目录中的文件。所有你需要知道的是文件名和根目录(主文件夹),这也适用于部分文件名,基本上如果你有三个文件命名为例如“pdf1”,“pdf2”和“pdf3”需要做的是向模式参数提供。
诚实地说,如果你知道你和你一起工作的目录和文件可以做得更容易,但看起来更像是矫枉过正,但这样做很简单。
基本上你提供在“目录”中的参数和文件夹路径中啪参数文件名
walk_directories("C:\\Example folder", "Example File.pdf") # or simply "pdf1" etc..
你会注意到这个函数返回一个变量,它是在这种情况下,完整的文件路径你正在使用的是什么。然后
_path = walk_directories("C:\\example folder", "example file.pdf")
_path将包含
C:\\example folder\\example file.pdf
,所以你可以像
def read(self, path):
try:
if os.path.isfile(path):
with open(path, 'r') as inFile:
temp = inFile.read()
except IOError as exception:
raise IOError('%s: %s' % (path, exception.strerror))
return temp
“路径” 参数会在这种情况下是_path产生的变量返回(临时)会从那里文件中包含的文本就像这样简单
def write(self, path, text):
try:
if os.path.isfile(path):
return None
else:
with open(path, 'w') as outFile:
outFile.write(text)
except IOError as exception:
raise IOError("%s: %s" % (path, exception.strerror))
return None
所以在这里它是非常直接的,以及提供包含要写入的文本的路径和变量。
可能的重复[在Python中查找扩展名为.txt的目录中的所有文件](http://stackoverflow.com/questions/3964681/find-all-files-in-directory-with-extension-txt-in- python) –
没有人这样说过。但希望你知道pdf的不是纯文本文件? – danidee