How Do I Open A Folder That Contains Files Within Another Folder
for example, Inside of Folder X there are Folders A, B, and C which contain each files. How can I create a loop that will go inside of each Fodler A, B, and C, and open the file i
Solution 1:
To modify the content of different file walking through its subdirectories, you can use os.walk and fnmatch - to choose the proper file format that you want to modify!
import os, fnmatch
def modify_file(filepath):
try:
with open(filepath) as f:
s = f.read()
s = your_method(s) # return modified content
if s:
with open(filepath, "w") as f: #write modified content to same file
print filepath
f.write(s)
f.flush()
f.close()
except:
import traceback
print traceback.format_exc()
def modifyFileInDirectory(directory, filePattern):
for path, dirs, files in os.walk(os.path.abspath(directory), followlinks=True):
for filename in fnmatch.filter(files, filePattern):
modify_file(filename)
modifyFileInDirectory(your_path,file_patter)
Solution 2:
If all of the files have the same name (say, result.txt
), the loop is fairly simple:
for subdir in ('A', 'B', 'C'):
path = 'X/{}/result.txt'.format(subdir)
with open(path, 'w') as fp:
fp.write("This is the result!\n")
Or, perhaps:
import os.path
for subdir in ('A', 'B', 'C'):
path = os.path.join('X', subdir, 'result.txt')
with open(path, 'w') as fp:
fp.write("This is the result!\n")
Update:
With the additional requirements listed in the comments, I recommend you use glob.glob()
, like so:
import os.path
import glob
for subdir in glob.glob("X/certain*"):
path = os.path.join(subdir, "result.txt")
with open(path, 'w') as fp:
fp.write("This is the result\n")
In the above example, the call to glob.glob()
will return a list of all of the subdirectories of X that begin with the literal text "certain". So, this loop might create, successively, "X/certainA/result.txt" and "X/certainBigHouse/result.txt", assuming that those subdirectories already exist.
Post a Comment for "How Do I Open A Folder That Contains Files Within Another Folder"