Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/python-2.7/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 2.7 无法在ZIP和gz中打开文件_Python 2.7_Zipfile_Os.path - Fatal编程技术网

Python 2.7 无法在ZIP和gz中打开文件

Python 2.7 无法在ZIP和gz中打开文件,python-2.7,zipfile,os.path,Python 2.7,Zipfile,Os.path,我试图读取拉链内的文件,但我得到 “IOError:[Errno 2]没有这样的文件或目录:” 我怀疑这与os.path.join有关。如果我添加“zname”的print语句,则不包括根目录的完整路径。 我创建了一个类似的函数,它可以完美地处理未压缩的文件,但如何在zips中实现这一点让我感到困惑。 任何帮助都将不胜感激。我是python新手,所以如果我错过了一些明显的东西,请原谅我 以下是代码和错误消息: def re_zip(): zcount = [] zpattern

我试图读取拉链内的文件,但我得到 “IOError:[Errno 2]没有这样的文件或目录:” 我怀疑这与os.path.join有关。如果我添加“zname”的print语句,则不包括根目录的完整路径。 我创建了一个类似的函数,它可以完美地处理未压缩的文件,但如何在zips中实现这一点让我感到困惑。 任何帮助都将不胜感激。我是python新手,所以如果我错过了一些明显的东西,请原谅我

以下是代码和错误消息:

def re_zip():
    zcount = []
    zpattern = ('.zip','.ZIP')
    for root, directories, filenames in os.walk(path):
        for filename in filenames:
            if filename.endswith(zpattern):
                zj = os.path.join(root,filename)
                zf = zipfile.ZipFile(zj)
                for zname in zf.namelist():
                    if zname.endswith(ext):
                        text = open(zname, 'r')
                        hits = 0
                        for line in text:
                            if re.match(regex, line):
                                hits = hits + 1
                        zcount.append(hits)
                        print (zname + " , " + str(hits))
                        output.write(str(hits) + " , " + zname + "\n")
                        text.close()    
    return(sum(zcount))

Traceback (most recent call last):
  File "re_count.py", line 80, in <module>
    total = re_match() + re_zip() + re_tar()
  File "re_count.py", line 45, in re_zip
    text = open(zname, 'r')
IOError: [Errno 2] No such file or directory: 'within_zip/folder/myfile.xml'
os.listdir()
类似,
namelist()
方法只返回不带根的文件名。您不能使用通常的
open()
函数,而是使用
zipfile.open()
方法,如下所示:

text = zf.open(zname)
os.listdir()
类似,
namelist()
方法只返回不带根的文件名。您不能使用通常的
open()
函数,而是使用
zipfile.open()
方法,如下所示:

text = zf.open(zname)

非常感谢。zf.open works。现在我正试图对tar gz文件执行相同的操作,我遇到了相同的问题。@trd不客气。别忘了投票并接受答案。谢谢!zf.open works。现在我正试图对tar gz文件执行相同的操作,我遇到了相同的问题。@trd不客气。别忘了投票并接受答案。