watch_folder = r'D:/zip' upload_url = 'http://192.168.1.226:6060/dz' def upload_file(file_path): with open(file_path, 'rb') as file: files = {'file': file} response = requests.post(upload_url, files=files) print(f"Uploaded {file_path}: {response.status_code}") def monitor_folder(): files = set() while True: current_files = set(os.listdir(watch_folder)) new_files = current_files - files for file in new_files: file_path = os.path.join(watch_folder, file) upload_file(file_path) files = current_files time.sleep(15) if __name__ == "__main__": monitor_folder() 加代码实现文件上传完成后将watch_folder = r'D:/zip'里的文件删除,而watch_folder = r'D:/zip'不动
时间: 2024-04-16 07:24:58 浏览: 196
要在文件上传完成后将 `watch_folder` 中的文件删除,可以在文件上传完成后使用 `os.remove()` 函数删除文件。以下是修改后的代码示例:
```python
import os
import time
import requests
watch_folder = r'D:/zip'
upload_url = 'http://192.168.1.226:6060/dz'
def upload_file(file_path):
with open(file_path, 'rb') as file:
files = {'file': file}
response = requests.post(upload_url, files=files)
print(f"Uploaded {file_path}: {response.status_code}")
def delete_file(file_path):
os.remove(file_path)
print(f"Deleted {file_path}")
def monitor_folder():
files = set()
while True:
current_files = set(os.listdir(watch_folder))
new_files = current_files - files
for file in new_files:
file_path = os.path.join(watch_folder, file)
upload_file(file_path)
delete_file(file_path)
files = current_files
time.sleep(15)
if __name__ == "__main__":
monitor_folder()
```
在上述代码中,我添加了一个名为 `delete_file()` 的新函数,用于删除已上传的文件。在上传完成后调用 `delete_file()` 函数,将已上传的文件从 `watch_folder` 中删除。
请注意,删除文件是一个不可逆的操作,请谨慎使用。确保你在明确了解代码功能和操作的情况下进行操作,并备份重要文件。
希望对你有所帮助!如果还有其他问题,请随时提问。
阅读全文