文件在之后丢失操作系统重命名()

2024-04-24 22:52:53 发布

您现在位置:Python中文网/ 问答频道 /正文

{{cd1>中从一个目录中提取出一个循环中的文件。它将每个.tar.gz中的内容提取到为每个.tar.gz创建的临时目录中,然后重命名它们,以便将它们移动到最终目录。在

为每个.tar.gz创建临时目录,以便只处理每个文件中的文件。重命名完成后,将删除临时目录,只为下一个.tar.gz再次创建临时目录。在

每个.tar.gz包含3个文件。这是保证,不是假设。在

所发生的是在重命名后,经检查,我可能会发现自己在最后的目录中缺少1-4个文件。例如,如果我从250个.tar.gz个文件开始,我应该有750个最终文件,但我可能只有746个。由于最终文件被重命名为与源文件相匹配.tar.gz,因此我可以返回并手动解压缩它以成功检索3个文件。在

需要找出os.rename()方法为什么会这样做。在

当前代码:

def unzip(in_dir):

    final_dir = os.path.abspath(os.path.join(in_dir, "UNZIPPED\\"))
    temp_dir = os.path.join(in_dir, "TEMP\\")

    os.mkdir(final_dir)

    files = [f for f in os.listdir(in_dir) if f.endswith('.tar.gz')]

    for item in files:
        os.mkdir(temp_dir)
        org_path = os.path.abspath(os.path.join(in_dir, item))
        tar = tarfile.open(org_path, 'r:gz')
        tar.extractall(path=temp_dir)
        tar.close()
        for member in os.listdir(temp_dir):
            new_path= os.path.abspath(os.path.join(temp_dir, member))
            os.rename(new_path, 
                      os.path.join(final_dir,
                                   os.path.basename(org_path)[:-7]+new_path[-4:]))
        os.rmdir(temp_dir)

如果我滥用os.path.abspath和/或{},请指出。我认为,通过将in_dir传递为C:\MyPath,那么使用os.path.join(in_dir, "UNZIPPED\\")将产生{},我不需要在它之前使用os.path.abspath。在


Tags: 文件pathinorg目录forosdir