繁体   English   中英

如何将zip文件移动到文件夹

[英]How to move a zip file to a folder

我有一个很大的没有。 zip文件的名称只是数字。 现在每个zip文件包含一个与zip文件同名的文件夹(即如果zip文件的名称是1234.zip,那么文件夹的名称也将是1234)。 此文件夹还包含一个文本文件,例如atextfile.txt,其中包含指定zip表示2016年的整数。
现在我想将每个zip文件移动到相应的文件夹,即年份。 意思是我想要做的是提取年份的值,即2016年,并创建一个名为2016的文件夹,将zip文件移动到此文件夹,并对下一个zip文件执行相同操作。
我成功地检索了年份并将其存储在名为year的变量中。
我到目前为止编写的代码:

    import glob
    import os
    import zipfile
    import shutil
    for zip_name in glob.glob('[0-9]*.zip'):
        z=zipfile.ZipFile(zip_name)
        # To remove '.zip' from the name of zip_name
        subdir = zip_name[:-4]
        with z.open('{}/atextfile.txt'.format(subdir)) as f:
            for line in f:
                for word in line:
                    year = word
                    # the file atextfile.txt has many lines containing many                        integer of which the first line represents the year.
                    break
                else:
                    continue
                break
        z.close()
        if not os.path.exists(year):
            os.makedirs(year)
        shutil.move(zip_name, year)


这是错误:
WindowsError:[错误32]进程无法访问该文件,因为它正被另一个进程使用。
我用Google搜索了一下,然后我才知道这背后的原因是因为我的zip文件已经打开了。 但我无法解决这个问题,所以请帮忙。
更新:问题解决了我将zip_name和year存储在一个文本文件中,然后在另一个程序中读取文本文件并将相应的zip文件移动到其年份文件夹。 谢谢你的回复。

尝试使用subprocess和ROBOCOPY:

import glob
import os
import zipfile
import subprocess

for zip_name in glob.glob('[0-9]*.zip'):
    z = zipfile.ZipFile(zip_name)
    # To remove '.zip' from the name of zip_name
    subdir = zip_name[:-4]
    with z.open('{}/atextfile.txt'.format(subdir)) as f:
        for line in f:
            for word in line:
                year = word
                break
            else:
                continue
            break
    z.close()
    if not os.path.exists(year):
        os.makedirs(year)
    command = 'ROBOCOPY {} {} /S /MOVE'.format(zip_name, year)
    subprocess.call(command)

以下对我有用,你今年的表现似乎有问题。

import glob
import os
import zipfile
import shutil

for zip_name in glob.glob('[0-9]*.zip'):
    z = zipfile.ZipFile(zip_name)
    subdir = os.path.splitext(zip_name)[0]

    with z.open('{}/atextfile.txt'.format(subdir)) as f:
        for line in f:
            line = line.strip()
            if line.lower().startswith("date"):
                year = line.split('-')[-1]
                break

    if not os.path.exists(year):
        os.makedirs(year)

    z.close()
    shutil.move(zip_name, year)

此外,最好使用os.path.splitext()函数来提取zip_name

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM