![](/img/trans.png)
[英]Writing a function to move two files with the same name (with different file extensions) to a folder with the same name in python
[英]How to delete one file from a folder, if two files with the same name and different ending exist in the same folder?
我正在努力弄清楚如何根據if
條件從一個文件夾中刪除文件。 此外,我也糊塗了自己做出了if
語句。
這是文件夾:
Desktop\Signed\
Desktop\to sign\
上述文件夾中的文件:
Desktop\Signed\
Document 1 User1.docx
Document 1 User2.docx
Desktop\to sign\
Document 2.docx
我有一個執行以下操作的應用程序:
Document 2.docx
。 我有多個用戶,在這種情況下我將使用User1
& User2
Signed
文件夾中創建一個文件,命名為: Document 2 User1.docx
保存后,樹線現在的樣子:
Desktop\Signed\ Document 1 User1.docx Document 1 User2.docx Document 2 User1.docx # New file Desktop\to sign\ Document 2.docx
一旦其他用戶簽名並點擊保存,樹線就會更改為:
Desktop\Signed\ Document 1 User1.docx Document 1 User2.docx Document 2 User1.docx # Previous New file Document 2 User2.docx # New file create Desktop\to sign\ #File removed becasue there are minimum of two files with same name and both users have signed it
這是在刪除文件的幕后工作的實際代碼:
#Usernames to verify 2 word documents exist
User1 = (signed+ os.path.basename(self.p).strip('.docx') +' User1'+ '.docx')
User2 = (signed + os.path.basename(self.p).strip('.docx') +' User2'+ '.docx')
……
if os.path.exists(User1) and os.path.exists(User2) or os.path.exists(User3) or os.path.exists(user4):
os.remove(to_sign + os.path.basename(self.p)) # Remove the to sign file if two users have signed it
Print("Both signed")
else:
print("One signed")
這可以正常工作,但這是我的實際問題。
如果其中一個用戶正在簽署文檔,例如User1
。
一旦他點擊保存,文檔就會在簽名文件夾中創建,並且to sign
的文件夾保持不變。
但是...如果他不小心再次按保存,則要to sign
的文件將被刪除。
這是因為 if 語句看到User1
文件已經存在並且只是將其刪除。 現在它已被刪除,我需要打開已簽名的文檔,清除所有內容並將其保存回to sign
文件夾以供其他用戶簽名,因為我至少需要兩個人簽名。
我怎樣才能避免這種情況?
這是我想出的:
創建一個if
語句來執行以下操作:檢查已signed
的文件夾是否有兩個名稱相同但結尾字符串不同的文件
我認為您需要在 if 語句的結尾添加== True
,但將多個用戶分成對,將它們編碼為 elif 語句。
if os.path.exists(User1) and os.path.exists(User2) == True:
os.remove(to_sign + os.path.basename(self.p)) # Remove the to sign file if two users have signed it
Print("Both signed")
elif ...: #add more users
else:
print("One signed")
您可以簡單地刪除== True
並通過以下方式獲得它:
if os.path.exists(User1) and os.path.exists(User2):
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.