我想将文件从 Zip 文件复制到单独的文件夹并同时读取该文件。如果我评论最后两行,该文件将复制到特定文件夹。
我尝试的代码是:
import os
import shutil
import zipfile
zip_filepath='/home/sundeep/Desktop/SCHEMA AUTOMATION/SOURCE/DSP8010_2017.1.zip'
target_dir='/home/sundeep/Desktop/SCHEMA AUTOMATION/SCHEMA'
with zipfile.ZipFile(zip_filepath) as z:
with z.open('DSP8010_2017.1/json-schema/AccountService.json') as zf, open(os.path.join(target_dir, os.path.basename('AccountService.json')), 'wb') as f:
shutil.copyfileobj(zf, f)
with open('AccountService.json') as json_data:
j=json.load(json_data)
但它给出了以下错误:
Traceback (most recent call last):
File "schema.py", line 21, in <module>
with open('AccountService.json') as json_data:
IOError: [Errno 2] No such file or directory: 'AccountService.json'
我的问题是否可以复制该文件并同时读取该文件的内容?
最佳答案
它对您不起作用的原因是,当您尝试读取该文件时,该文件尚未关闭(写入磁盘)。
有两种方法可以解决此问题 - 一种是将最后一个 with
语句移到第一个 with
语句之外:
with zipfile.ZipFile(zip_filepath) as z:
with z.open('DSP8010_2017.1/json-schema/AccountService.json') as zf, open(os.path.join(target_dir, os.path.basename('AccountService.json')), 'wb') as f:
shutil.copyfileobj(zf, f)
with open('AccountService.json') as json_data:
j=json.load(json_data)
这样,您的文件就应该被写入并可供您使用。
但是,更简单的方法是在复制 zip 文件之前读取其内容:
with zipfile.ZipFile(zip_filepath) as z:
with z.open('DSP8010_2017.1/json-schema/AccountService.json') as zf, open(os.path.join(target_dir, os.path.basename('AccountService.json')), 'wb') as f:
j = json.load(zf) # read the contents here.
shutil.copyfileobj(zf, f) # copy the file
#with open('AccountService.json') as json_data:
# j=json.load(json_data)
现在,您不再需要打开其他文件。
关于python - 从 zip 复制文件并同时读取该文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49355830/