【问题标题】:Not checking file size correctly未正确检查文件大小
【发布时间】:2015-08-21 17:56:06
【问题描述】:

我编写了一个简单的脚本,用于将下载目录中的电影在完成下载后移动到他们需要去的位置,并提出一个简单的问题。

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

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

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

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)

【问题讨论】:

  • 您使用什么程序下载文件?如果它事先知道下载的文件大小(通常是通过网络下载时的情况),它分配一个大小合适的文件并在它进入时用数据覆盖它会更有效,这意味着大小磁盘上的内容总是相同的。
  • 您使用的是什么操作系统?

标签: python file python-3.x file-io operating-system


【解决方案1】:

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

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

【讨论】:

  • 我发现的唯一解决方法,但仍然不起作用,是检查磁盘的可用空间,其中包括可能不一定是使用 shutil.disk_usage() 检查自身的文件或psutil.disk_usage()
【解决方案2】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-12-16
    • 2012-02-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多