没有正确检查文件大小

Not checking file size correctly

我写了一个简单的脚本来移动我的下载目录中的电影,一旦他们完成下载,到他们需要去的位置并有一个简单的问题。

也许我不明白 os 模块是如何处理文件的当前大小的,但它没有返回正确的文件大小。它返回下载文件的完整大小,而不是硬盘上文件的大小,因为这将是我需要比较的下载大小。有没有办法解决这个问题,或者执行更好的检查?

我已经评论了相关行,并且在评论中它 returns 在使用 time.sleep 等待 30 秒后大小相同,但实际下载的部分要大得多。

如评论中所述,文件大小是在下载之前分配的,因此这不起作用。

def check_size(file_path):
    check = False
    previous_size = os.path.getsize(file_path) # first check
    print("The current size of the movie at %s is: " %  time.strftime("%I:%M:%S"), previous_size)
    time.sleep(30)
    new_size = os.path.getsize(file_path) #30 secs later same size as first check, but downloaded size ~100 mb greater?
    print("The current size of the movie at %s is: " % time.strftime("%I:%M:%S"), new_size)
    if previous_size == new_size:
         check = True
    return check

def move_movies(source, file_extension, sub_string):
    while process_running():
        for dirpath, dirnames, filenames in os.walk(source):
            for a_file in filenames:
                if (a_file.endswith(file_extension) and sub_string in a_file):
                    path = dirpath + "\" +  a_file
                    print("Checking the movie:", a_file, "for moving")
                    if check_size(path):  
                        print("Moving the movie: ", a_file)
                        shutil.move(dirpath, some destination path)

作为检查大小最近是否更改的替代方法,您可以检查文件的修改时间:

import os,time
def getAge(path):
    """ returns the age of the file in seconds """
    return (time.time() - os.stat(path).st_mtime)

或者您可以对文件进行内存映射(使用 mmap)。首先找到文件中的最后一个非零字节,然后检查之后是否有任何其他字节发生变化。

如果您想查看该文件是否仍由另一个进程打开,您可以使用 lsof(您需要打开一个子进程来调用它)。不过,这可能只适用于类 unix 操作系统,我不知道是否有 windows 等效项。