我在一個檔案夾中有5個excel檔案,我想一個一個一個一個地編輯,一個下一個檔案只關閉上一個檔案。
所以首先我使用 glob 讀取檔案夾中的所有檔案。
inputsFiles = glob.glob('Sub_Inputs/[a-z]*xlsx')
輸出
['Sub_Inputs\\Buses.xlsx', 'Sub_Inputs\\Load_Profile.xlsx', 'Sub_Inputs\\Solar_Profile.xlsx', 'Sub_Inputs\\Time_frame.xlsx', 'Sub_Inputs\\Wind_Profile.xlsx']
之后我打開它們:
for i in inputsFiles:
print('Please fill the details related to ' os.path.basename(i)[:-5])
# print(i)
os.system("start EXCEL.EXE " i)
但這將打開所有檔案。我試圖檢查檔案是否已經打開,但在這種情況下不起作用:
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.")
這不起作用,有人可以幫忙嗎?我只想在前一個關閉時打開檔案。
uj5u.com熱心網友回復:
我認為 os.system 與您的論點似乎不起作用。您可以嘗試以下操作:
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))
或者類似的東西。
或者,您可以使用 Python 的subprocess,人們似乎更喜歡它(請參閱此 SO 問題))。我不能告訴你為什么 1 比另一個更受歡迎。
編輯:
這樣做的一種(非常丑陋的)方式可能是這樣的:
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
雖然丑陋,但它在技術上應該可以作業,因為回圈會暫停,直到用戶提供一些輸入。還有一個os.system像這樣的作業系統:
os.system('read -s -n 1 -p "Press any key to continue..."')
我對后者沒有經驗,所以不知道這是否有效。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/366314.html
