如何使用从输入中获取的文件名保存工作簿

How can I save a workbook with a filename taken from an input

我编写了一个程序,从一个 sheet 中获取数据并将其粘贴到另一个 sheet 中。但是,当我尝试保存工作簿时,出现错误。文件名应该与在上一行中输入的文件名相同,但我不确定如何使工作簿的保存功能起作用。我试过使用变量输入和它的 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)

您在代码中使用变量名 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