Python自动化:文件管理器
我创建了一个脚本来自动排序我的下载目录。基本上,我希望它在后台运行,对我下载的每个文件进行排序,并将其移动到正确的文件夹中 问题是,当脚本运行时,下载总是失败。我认为这可能是因为当chrome开始下载时,它会创建一个临时文件。并且仅在下载完成时显示整个文件。我添加了排除“crdownload”文件的条件。但是,当我尝试下载文件时,它会一直下载到最后并失败 我怎样才能解决这个问题 以下是脚本:Python自动化:文件管理器,python,Python,我创建了一个脚本来自动排序我的下载目录。基本上,我希望它在后台运行,对我下载的每个文件进行排序,并将其移动到正确的文件夹中 问题是,当脚本运行时,下载总是失败。我认为这可能是因为当chrome开始下载时,它会创建一个临时文件。并且仅在下载完成时显示整个文件。我添加了排除“crdownload”文件的条件。但是,当我尝试下载文件时,它会一直下载到最后并失败 我怎样才能解决这个问题 以下是脚本: #!/bin/python2.7 # pip install watchdog fro theses
#!/bin/python2.7
# pip install watchdog fro theses package to work
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
import os
import json
import time
import datetime
ROOT_DIR = '/home/xxx/Downloads/'
assertMsg = ''' File \'%s\' don\'t exists. Abord ... ''' % (ROOT_DIR)
# make sure directory exists before starting the application
assert os.path.exists(ROOT_DIR), assertMsg
# + datetime.datetime.now().strftime("%Y-%m-%dT%H:%M:%S_")
# /home/xxx/Downloads
# chrome Unconfirmed 332952.crdownload
class MyHandler(FileSystemEventHandler):
def on_modified(self, event):
today_date = datetime.datetime.now().strftime("%Y-%m-%d")
files = [f for f in os.listdir(ROOT_DIR) if os.path.isfile(ROOT_DIR + f)]
for filename in files:
name, ext = os.path.splitext(filename) # get file extention
if ext == 'crdownload':
continue
if not ext:
ext = 'others'
ext = ext.strip('.')
ext = ext.lower()
source_file = ROOT_DIR + filename
new_destination = ROOT_DIR + ext + "/" + today_date + "/" + filename
if not os.path.exists(ROOT_DIR + ext):
os.mkdir(ROOT_DIR + ext)
os.mkdir(ROOT_DIR + ext + "/" + today_date)
else:
if not os.path.exists(ROOT_DIR + ext + "/" + today_date):
os.mkdir(ROOT_DIR + ext + "/" + today_date)
os.rename(source_file, new_destination)
folder_to_track = ROOT_DIR
folder_destination = ROOT_DIR
event_handler = MyHandler()
observer = Observer()
observer.schedule(event_handler, folder_to_track, recursive=True)
observer.start()
try:
while True:
time.sleep(60)
except KeyboardInterrupt:
observer.stop()
observer.join()
observer.join()
下载失败:
好的,我复制并发现了发生的事情。实际上,您的
如果ext==“crdownload”:
从未满足。你要么把它改成
if ext == '.crdownload':
或者改变这一点:
name, ext = filename.split('.')
您正在检查
ext
是否等于crdownload
,但您的ext
是.crdownload
。您应该想象,当脚本创建名为crdownload
的文件夹时,这意味着它没有通过此步骤。为什么失败?你有例外吗?您是否尝试下载某些内容并使用调试器进行测试,以逐步了解该过程?不按预期工作是什么意思?@KostasCharitidis下载失败