So I hope I'm understanding you correctly, and if I am this should help.
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
This was made for a different purpose but it should suit your needs as well, I got this going to locate files contained in "unknown" sub-directories contained within a single root directory. All you need to know is the filename and the root directory( main folder) this will work with partial filenames as well, essentially if you've got three files named for instance "pdf1", "pdf2", and "pdf3" all you need to do is supply that to the pattern parameter.
In honesty, this seems more like overkill if you know the directories and files you're working with you could do it a lot easier but with this, it's pretty straight forward.
Essentially you supply the folder path in the "Dir" Parameter and the filename in the Patter parameter
walk_directories("C:\\Example folder", "Example File.pdf") # or simply "pdf1" etc..
You'll note this function returns a variable which is, in this case, the full file path of what you're working with.
_path = walk_directories("C:\\example folder", "example file.pdf")
_path would then contain
C:\\example folder\\example file.pdf
So you could something like
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
The "path" parameter would in this case be _path the resulting variable returned (temp) would be the text that was contained in the file from there it's as simple as
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
so here it's pretty straight forward as well supply the path and the variable containing the text you want to write.