[英]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. 在文件夹X内部有文件夹A,B和C,其中包含每个文件。
How can I create a loop that will go inside of each Fodler A, B, and C, and open the file i need in write mode to make some changes? 如何创建一个将进入每个Fodler A,B和C的循环,并在写入模式下打开我需要的文件进行一些更改?
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! 要修改遍历其子目录的不同文件的内容,可以使用os.walk和fnmatch - 选择要修改的正确文件格式!
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)
If all of the files have the same name (say, result.txt
), the loop is fairly simple: 如果所有文件都具有相同的名称(例如
result.txt
),则循环非常简单:
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")
With the additional requirements listed in the comments, I recommend you use glob.glob()
, like so: 根据评论中列出的其他要求,我建议您使用
glob.glob()
,如下所示:
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". 在上面的示例中,对
glob.glob()
的调用将返回以文字文本“确定”开头的X的所有子目录的列表。 So, this loop might create, successively, "X/certainA/result.txt" and "X/certainBigHouse/result.txt", assuming that those subdirectories already exist. 因此,这个循环可能会连续创建“X / certainA / result.txt”和“X / certainBigHouse / result.txt”,假设这些子目录已经存在。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.