简体   繁体   English

如何打开包含其他文件夹中的文件的文件夹

[英]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")

Update: 更新:

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.

相关问题 如何将一种特定类型的所有文件从一个文件夹复制到Python中的另一个文件夹 - How do I copy all files of one specific type from a folder to another folder in Python 如何在 Python 3 中的特定条件下搜索要移动到另一个文件夹的文件夹中的文件? - How do I search files in a folder to be moved to another folder in a certain condition in Python 3? 如何打开文件夹中的第一个文件 - How do I open the first file in a folder filedialog打开文件夹中的文件(tkinter) - filedialog to open files within a folder (tkinter) Python:如何让python从其文件夹中打开文件? - Python: How do I get python to open files out of it's folder? 如何从一个文件夹中的 n 个 csv 文件导入数据? - How do I import data from n number of csv files within a folder? 如何在一个特定的文件夹中打开多个.nc文件? - How do you open multiple .nc files in a particular folder? 如何从另一个文件夹打开 json 文件? - How can I open a json file from another folder? 我将文件(.jpg)保存在另一个文件夹中,我想在我的 python 程序中使用该文件。 我如何导入它们 - i save files(.jpg) in another folder and i want to use that files in my python program. how do i import them 如何正确打开文件夹中的图像以进行处理? - How do I properly open an image from a folder to process it?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM