Home > Back-end >  How can I save a workbook with a filename taken from an input
How can I save a workbook with a filename taken from an input

Time:11-09

I wrote a program that takes data from one sheet and pastes it in another sheet. However, when I try saving the workbook, it gives me an error. The filename name should be the same as one that gets inputted in a previous line but I'm not sure how to make the save function work for the workbook. I've tried using the variable input and the str of it but neither worked.

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)

CodePudding user response:

You're using the variable name unit_list to mean two different things in your code. First it's the filename, then it's the whole workbook you open from that filename.

The line where you try to save the workbook tries to use both meanings:

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

Try something like this:

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
  • Related