[英]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.