Home > Software design >  How to edit all excel file in a folder one after another with python?
How to edit all excel file in a folder one after another with python?

Time:11-26

I have 5 excel files in a folder, which I want to edit one by one and one by one means, one the next file only the previous file is closes.


So first I read all the files in a folder using glob.

inputsFiles = glob.glob('Sub_Inputs/[a-z]*xlsx')

output

['Sub_Inputs\\Buses.xlsx', 'Sub_Inputs\\Load_Profile.xlsx', 'Sub_Inputs\\Solar_Profile.xlsx', 'Sub_Inputs\\Time_frame.xlsx', 'Sub_Inputs\\Wind_Profile.xlsx']

after that I opened them:

for i in inputsFiles:
    print('Please fill the details related to '   os.path.basename(i)[:-5])
    # print(i)
    os.system("start EXCEL.EXE " i)

But this will open all the files. I tried to check if the file is already open or not but that is not working in this condition:

try:
    with open("filename", "r") as file:
        # Print the success message
        print("File has opened for reading.")
# Raise error if the file is opened before
except IOError:
    print("File has opened already.")

this is not working, can anyone please help? I want to open the file only when the previous one is closed.

CodePudding user response:

I think the os.system with your argument does not seem to work. You could try the following:

for i in inputsFiles:
    print('Please fill the details related to '   os.path.basename(i)[:-5])
    # print(i)
    os.system("start EXCEL.EXE {}".format(i))

Or something similar.

Alternatively you could use Python's subprocess, which people seem to prefer (see this SO question)). I can't tell you why 1 is preferred over the other though.


edit:

One (very ugly) way of doing this might be like so:

for i in inputsFiles:
    try:
        print('Please fill the details related to '   os.path.basename(i)[:-5])
        # print(i)
        os.system("start EXCEL.EXE {}".format(i))
        input("Press enter to open the new document ")
    except SyntaxError:
        pass

Though ugly, it should technically work because the loop is suspended until the user provides some input. There is also a OS thing in os.system like so:

os.system('read -s -n 1 -p "Press any key to continue..."')

I have no experience with the latter so don't know if this works.

  • Related