قراءة محتويات ملف القطران دون ما يصل إليها، في برنامج نصي بيثون

StackOverflow https://stackoverflow.com/questions/2018512

  •  19-09-2019
  •  | 
  •  

سؤال

لدي ملف قطران لديه عدد من الملفات داخله. أحتاج إلى كتابة برنامج نصي Python الذي سيؤدي إلى قراءة محتويات الملفات ويعطي العد o الأحرف الإجمالية، بما في ذلك العدد الإجمالي للأحرف والمسافات وأحرف خطوط نيولينية وكل شيء وبدون ملف القطران.

هل كانت مفيدة؟

المحلول

يمكنك استخدام GetMembers ()

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

بعد ذلك، يمكنك استخدام chectsfile () لاستخراج الأعضاء ككائن ملف. مجرد مثال

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" في المثال أعلاه، يمكنك استخدام قراءة ()، وقراءة () إلخ.

نصائح أخرى

تحتاج إلى استخدام وحدة 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 الوصول إلى عضو أرشيف القطران عبر اسم الملف مثل ذلك

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

الاعتمادات:

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top