【问题标题】:How can I save a workbook with a filename taken from an input如何使用从输入中获取的文件名保存工作簿
【发布时间】:2021-11-09 01:28:09
【问题描述】:

我编写了一个程序,它从一张纸上获取数据并将其粘贴到另一张纸上。但是,当我尝试保存工作簿时,它给了我一个错误。文件名名称应与在前一行中输入的名称相同,但我不确定如何使保存功能适用于工作簿。我试过使用变量 input 和它的 str 但都没有成功。

unit_list = input("Please enter the file name: ")
unit_list = load_workbook(unit_list)
all_units = unit_list["Sheet1"]
picked_units = unit_list["Sheet2"]

row_count = all_units.max_row
col_count = all_units.max_column

need_units = int(input("How many units need to be checked? "))

nul = []

while len(nul)+1 <= need_units:
    unit = rand_seed(row_count)
    if unit not in nul:
        nul.append(unit)
        for j in range(1, col_count+1):
            c = all_units.cell(row=unit+1, column=j)
            picked_units.cell(row=len(nul), column=j).value = c.value

unit_list.save(filename=unit_list)

【问题讨论】:

    标签: python excel openpyxl


    【解决方案1】:

    您在代码中使用变量名称unit_list 来表示两种不同的东西。首先是文件名,然后是您从该文件名打开的整个工作簿。

    您尝试保存工作簿的行尝试使用这两种含义:

    unit_list = input("Please enter the file name: ")   # first use
    unit_list = load_workbook(unit_list)                # second use
    
    #...
    
    unit_list.save(filename=unit_list)  # this needs to refer to the both versions of unit_list
    

    试试这样的:

    filename = input("Please enter the file name: ")   # new name for this variable
    unit_list = load_workbook(filename)                # use it here
    
    #...
    
    unit_list.save(filename=filename)   # now we have two different variables to use down here
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-24
      • 2023-02-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多