IT TIP

python 스크립트에서 tar 파일 내용을 압축 해제하지 않고 읽기

itqueen 2020. 11. 4. 21:04
반응형

python 스크립트에서 tar 파일 내용을 압축 해제하지 않고 읽기


그 안에 많은 파일이있는 tar 파일이 있습니다. 파일의 내용을 읽고 tar 파일의 압축을 풀지 않고 총 문자, 공백, 개행 문자, 모든 것을 포함하여 총 문자 수를 제공하는 파이썬 스크립트를 작성해야합니다.


getmembers () 사용할 수 있습니다.

>>> import  tarfile
>>> tar = tarfile.open("test.tar")
>>> tar.getmembers()

그런 다음 extractfile ()을 사용하여 멤버를 파일 객체로 추출 할 수 있습니다. 단지 예

import tarfile,os
import sys
os.chdir("/tmp/foo")
tar = tarfile.open("test.tar")
for member in tar.getmembers():
    f=tar.extractfile(member)
    content=f.read()
    print "%s has %d newlines" %(member, content.count("\n"))
    print "%s has %d spaces" % (member,content.count(" "))
    print "%s has %d characters" % (member, len(content))
    sys.exit()
tar.close()

위의 예에서 파일 객체 "f"를 사용하면 read (), readlines () 등을 사용할 수 있습니다.


tarfile 모듈을 사용해야합니다. 특히 TarFile 클래스의 인스턴스를 사용하여 파일에 액세스 한 다음 TarFile.getnames ()로 이름에 액세스합니다.

 |  getnames(self)
 |      Return the members of the archive as a list of their names. It has
 |      the same order as the list returned by getmembers().

대신 내용 을 읽으려면 이 방법을 사용합니다.

 |  extractfile(self, member)
 |      Extract a member from the archive as a file object. `member' may be
 |      a filename or a TarInfo object. If `member' is a regular file, a
 |      file-like object is returned. If `member' is a link, a file-like
 |      object is constructed from the link's target. If `member' is none of
 |      the above, None is returned.
 |      The file-like object is read-only and provides the following
 |      methods: read(), readline(), readlines(), seek() and tell()

@ stefano-borini가 언급 한 방법의 구현 다음과 같은 파일 이름을 통해 tar 아카이브 멤버에 액세스

#python3
myFile = myArchive.extractfile( 
    dict(zip(
        myArchive.getnames(), 
        myArchive.getmembers()
    ))['path/to/file'] 
).read()`

크레딧 :

참고 URL : https://stackoverflow.com/questions/2018512/reading-tar-file-contents-without-untarring-it-in-python-script

반응형