반응형
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()`
크레딧 :
dict(zip(에서 https://stackoverflow.com/a/209854/1695680tarfile.getnames에서 https://stackoverflow.com/a/2018523/1695680- 또한 내 용도로 버퍼에서 tar 아카이브 읽기 Python 3의 바이트 버퍼에서 메모리에 TarFile 객체를 생성하는 방법은 무엇입니까?
반응형
'IT TIP' 카테고리의 다른 글
| Criteria API를 사용하여 주문 (0) | 2020.11.04 |
|---|---|
| WCF 오류 "HTTP.SYS를 사용하여 HTTPS의 경우 서버 인증서가 제대로 구성되지 않았기 때문일 수 있습니다." (0) | 2020.11.04 |
| TortoiseSVN의 Windows 탐색기 아이콘이 상태를 수정하기 위해 새로 고치는 데 오랜 시간이 걸립니다. (0) | 2020.11.04 |
| .NET의 String.Normalize는 무엇을합니까? (0) | 2020.11.04 |
| Razor보기 파일 내에서 일반 구문을 사용하는 방법은 무엇입니까? (0) | 2020.11.04 |