繁体   English   中英

Python 使用循环打开和保存多个文件

[英]Python open and saving multiple files using loops

下面的代码将打开源文件,并将其复制到模板,然后将文件另存为新名称。 我想在这个脚本中添加多个 for 循环。

我有 27 个文件要打开,分别粘贴到模板中,每次都保存为不同的名称。

我不想每次都输入源文件名,并且每次都更新保存。 我不确定如何修改以下脚本以使其正常工作。

Examples Source Files:
NNB-6a_v1_T01-Report.xlsx
NNB-6a_v1_T02-Report.xlsx
NNB-6a_v1_T03-Report.xlsx
NNB-6a_v1_P01-Report.xlsx
NNB-6a_v1_P02-Report.xlsx
NNB-6a_v1_P03-Report.xlsx

Paste source data one by one into template - then save each as

Example Save as:
Report_6a_v1_T01.xlsx
Report_6a_v1_T02.xlsx
Report_6a_v1_T03.xlsx
Report_6a_v1_P01.xlsx
Report_6a_v1_P02.xlsx
Report_6a_v1_P03.xlsx

     import openpyxl as xl; 
        import glob
        import pandas as pd



        # opening the source excel file 
        filename ="C:/NNB-6a_v1_T01-Report.xlsx"
        wb1 = xl.load_workbook(filename) 
        ws1 = wb1.worksheets[1] 

        # opening the destination excel file  
        filename1 ="C:/Template.xlsx"
        wb2 = xl.load_workbook(filename1) 
        ws2 = wb2.worksheets[2] 

        # calculate total number of rows and  
        # columns in source excel file 
        mr = ws1.max_row 
        mc = ws1.max_column 

        # copying the cell values from source  
        # excel file to destination excel file 
        for i in range (1, mr + 1): 
            for j in range (1, mc + 1): 
                # reading cell value from source excel file 
                c = ws1.cell(row = i, column = j) 

                ws2.cell(row = i+12, column = j+1).value = c.value 

        # saving the destination excel file 
        wb2.save('C:/Report_6a_v1_T01.xlsx')

假设您所有的文件都在目录dir中,您可以使用os package 来获取列表中文件的名称。 由于您只是在寻找xlsx文件,因此可以相应地过滤文件名。 一旦您在列表中获得了文件的名称,您就可以遍历它,并执行您的 excel 操作: 示例代码:

import os
#import rest of the pkgs

#fetch the filenames from current directory
files = [file for file in os.listdir('.') if os.path.isfile(file) and file.endswith('.xlsx')]

#make a separate directory for reports
os.mkdir('./reports')

for file in files:
    #loop through files and do your operation
    #save to reports directory
    report_name = file + '_report'
    wb.save('./reports/'+report_name+'.xlsx')

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM