Python 从zip复制文件,同时读取该文件
我想将一个文件从Zip文件复制到另一个文件夹,同时读取该文件。如果我对最后两行进行注释,文件将复制到特定文件夹 我尝试的代码是:Python 从zip复制文件,同时读取该文件,python,zipfile,Python,Zipfile,我想将一个文件从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' wi
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'
回溯(最近一次呼叫最后一次):
文件“schema.py”,第21行,在
使用open('AccountService.json')作为json_数据:
IOError:[Errno 2]没有这样的文件或目录:“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)
现在,您不需要再打开另一个文件。非常感谢您。。。我可以同时编辑该文件的内容吗?你可以对内容做任何你喜欢的事情;但是,请确保将修改后的内容写入目标文件,而不仅仅是复制它(否则,您的更改将被覆盖)。