0

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.

Vesper
  • 795
  • 1
  • 9
  • 21

1 Answers1

1

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.

JustLudo
  • 1,690
  • 12
  • 29
  • Yeah thanks, but this will open all the files simultaneously which leads to my original question that can I open them one by one and one by one means, open the next file only when the previous one is closed – Vesper Nov 25 '21 at 09:48
  • Ow I now see why. The loop does of course not wait for input. Since the program is supposed to know when the user quits the application you could either find that trigger (but that might be hard), or you could suspend the loop by opening the document and right after that wait for user input. This would mean that the user would have to press enter or type something manually before the loop will continue. – JustLudo Nov 25 '21 at 10:23
  • Edited my answer accordingly. – JustLudo Nov 25 '21 at 10:28