Skip to main content
 首页 » 编程设计

python之在 python 中创建一个临时文件数组

2025年05月04日11langtianya

我正在尝试使用 NamedTempopraryFile 创建一个临时文件数组,但它似乎没有按我预期的方式工作。只创建一个临时文件并且函数返回,而不是 db_file_paths 中有许多元素。

有没有人看到什么不对?

示例输入:db_file_path = ["/mnt/somedir/data_0",/mnt/somedir/data_1"]

def create_ini(db_file_paths): 
 
    #array of file tmpfs ini filehandles 
    file_handles = [] 
 
    for path in db_file_paths: 
        #make a tempfs file handle 
        f_handle = tempfile.NamedTemporaryFile(delete=False) 
        #match and replace db dummy file path 
        f_handle = replace( f_handle.name, source_ini, pattern, path ) 
        file_handles.append(f_handle) 
        return file_handles 

请您参考如下方法:

您在 for 循环的第一次迭代结束时返回。重新缩进最后一行,以便仅在 for 循环结束后执行。

def create_ini(db_file_paths): 
 
    #array of file tmpfs ini filehandles 
    file_handles = [] 
 
    for path in db_file_paths: 
        #make a tempfs file handle 
        f_handle = tempfile.NamedTemporaryFile(delete=False) 
        #match and replace db dummy file path 
        f_handle = replace( f_handle.name, source_ini, pattern, path ) 
        file_handles.append(f_handle) 
    return file_handles # <-- change of indentation here