我正试图读取拉链内的文件,但我得到了 “IOError:[Errno 2]没有这样的文件或目录:” 我怀疑它与os.path.join有关。如果我添加“zname”的print语句,则不包括根目录的完整路径。 我创建了一个类似的功能,非常适合未压缩的文件,但我很难理解如何在拉链中使这个工作。 任何帮助将不胜感激。我是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'
通过将text = open(zname,'r')更改为text = zf.open(zname,'r')来修复re_zip()
现在我正在尝试使用tar gz文件。我得到了tar或tar.gz的相同错误。我相信tar模块应该处理两者。
def re_tar():
tcount = []
tars = ('tar','gz','tgz','TAR','GZ')
for root, directories, filenames in os.walk(path):
for filename in filenames:
if filename.endswith(tars):
tj = os.path.join(root,filename)
tf = tarfile.open(tj)
for tarinfo in tf.getmembers():
tname = tarinfo.name
if tname.endswith(ext):
text = tf.open(tname, 'r')
hits = 0
for line in text:
if re.match(regex, line):
hits = hits + 1
tcount.append(hits)
print (tname + " , " + str(hits))
output.write(str(hits) + " , " + tname + "\n")
text.close()
tf.close()
return(sum(tcount))
File "re_count_v2.py", line 68, in re_tar
text = tf.open(tname, 'r')
File "C:\Users\username\AppData\Local\Continuum\Anaconda2\lib\tarfile.py", line 1673, in open
return func(name, "r", fileobj, **kwargs)
File "C:\Users\username\AppData\Local\Continuum\Anaconda2\lib\tarfile.py", line 1738, in gzopen
fileobj = gzip.GzipFile(name, mode, compresslevel, fileobj)
File "C:\Users\username\AppData\Local\Continuum\Anaconda2\lib\gzip.py", line 94, in __init__
fileobj = self.myfileobj = __builtin__.open(filename, mode or 'rb')
IOError: [Errno 2] No such file or directory: 'httpopenaccessikuedutr8080oai_.scol11413101_1.xml'
答案 0 :(得分:0)
与os.listdir()
类似,namelist()
方法仅返回没有root的文件名。您无法使用通常的open()
函数,而是使用zipfile.open()
方法,如下所示:
text = zf.open(zname)