如何打开另一个文件夹中包含文件的文件夹

2024-04-24 22:34:08 发布

您现在位置:Python中文网/ 问答频道 /正文

例如

在文件夹X中有文件夹A、B和C,其中包含每个文件。在

如何创建一个循环,进入每个Fodler a、B和C的内部,并在写入模式下打开所需的文件以进行一些更改?在


Tags: 文件文件夹模式fodler
2条回答

如果所有文件都有相同的名称(比如,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")

或者,也许:

^{pr2}$

更新:

对于注释中列出的附加要求,我建议您使用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")

在上面的例子中,对glob.glob()的调用将返回X的所有子目录的列表,这些子目录以文本“searent”开头。所以,这个循环可能会连续地创建“X/certainA/结果.txt“和”X/certainBigHouse/结果.txt,假设这些子目录已经存在。在

要修改遍历其子目录的不同文件的内容,可以使用手术室步行和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)

相关问题 更多 >