У меня есть файл tar, который имеет количество файлов в нем. Я должен записать сценарий Python, который считает содержание файлов и дает общие символы количества o, включая общее количество букв, пробелов, символов новой строки, всего, не не смоля файл tar.
можно использовать getmember()
>>> 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() и т.п.
необходимо использовать модуль tar-файла. В частности, вы используете экземпляр класса 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()