Если файлы являются достаточно маленькими, можно хлебать их обоих в Perl и иметь его regex механизм, добейтесь цели:
perl -0777e '
open "$FILE1","<","file_1";
open "$FILE2","<","file_2";
$file_1 = <$FILE1>;
$file_2 = <$FILE2>;
print "file_2 is", $file_1 =~ /\Q$file_2\E/ ? "" : "not";
print " a subset of file_1\n";
'
-0777
переключатель дает Perl команду устанавливать свой входной разделитель записей $/
к неопределенному значению, чтобы хлебать файлы полностью.
Сценарий питона в конце этого ответа не делает то, что вы хотите, но должен подойти поближе. Я добавил каталог 10999
, чтобы показать, как отображаются каталоги одного уровня.
Этот код не очень хорошо работает с подкаталогами в zip-файле, для этого вы...
лучше всего написать рутину zip_recurse, которая может называть себя рекурсивной.
Код был протестирован на работу с Python 2.6.9, 2.7.9, 3.3.6 и 3.4.2
$ mkdir -p sdc/QA/SP/data/10507
$ echo -e '01 line 1\n01 line 2\n01 line 3' > sdc/QA/SP/data/10507/01.txt
$ echo -e '02 line 1\n02 line 2\n02 line 3' > sdc/QA/SP/data/10507/02.txt
$ echo -e '03 line 1\n03 line 2\n03 line 3' > sdc/QA/SP/data/10507/03.txt
$ mkdir -p sdc/QA/SP/data/10999
$ echo -e '04 line 1\n04 line 2\n04 line 3' > sdc/QA/SP/data/10999/04.txt
$ pushd sdc/QA/SP/data/10507/
$ zip 03.zip *.txt
$ rm 03.txt
$ popd
$ python test.py sdc
└── QA/
└── SP/
└── data/
├── 10507/
│ ├── 01.txt: 01 line 1\n: 01 line 2\n
│ ├── 02.txt: 02 line 1\n: 02 line 2\n
│ └── 03.zip
│ └── 01.txt: 01 line 1\n01 line 2\n
│ └── 02.txt: 02 line 1\n02 line 2\n
│ └── 03.txt: 03 line 1\n03 line 2\n
└── 10999/
└── 04.txt: 04 line 1\n: 04 line 2\n
test.py
:
#! /usr/bin/env python
# coding: utf-8
from __future__ import with_statement
import sys
import os
from zipfile import ZipFile
class ListTree:
# tree characters
indent = 2
def __init__(self, characters=None):
""" characters should be None for graphical, "ASCII" for non
graphical (+|`-) or a four letter sequence
"""
if characters is None:
self._char = u'├│└─'
elif characters == 'ASCII':
self._char = '+|`-'
else:
self._char == characters
assert len(self._char) == 4
def out(self, endmarkers, val, fp=None):
# endmarkers is a list with the length of the list indicating
# the depth and True values if at that depth this entry is the last one
stream = fp if fp else sys.stdout
s = u''
for idx, n in enumerate(endmarkers):
if idx == len(endmarkers) - 1:
if n:
s += self._char[2] + self._char[3] * self.indent
else:
s += self._char[0] + self._char[3] * self.indent
else: # not last one
if n:
s += ' ' * (self.indent + 2)
else:
s += self._char[1] + ' ' * (self.indent + 1)
msg = u'{0} {1}\n'.format(s, val)
if sys.version_info < (3,):
msg = msg.encode('utf-8')
stream.write(msg)
class WalkTree(object):
def __init__(self, base_dir):
lt = ListTree()
old_dir = os.getcwd()
os.chdir(base_dir)
for n, x in self.recurse('.'):
lt.out(n, x)
os.chdir(old_dir)
def recurse(self, path, prev=[]):
# could use os.walk() but would have to combine the dir and file_name
# lists, sort them and split apart, or keep the lists sorted separate
# and check from which one to take the next entry
lst = sorted(
[x for x in os.listdir(path) if x and not x[0] == '.'])
lidx = len(lst) - 1
for idx, x in enumerate(lst):
n = prev[:] + [idx == lidx]
dpath = os.path.join(path, x)
if os.path.isdir(dpath):
x += '/'
yield n, x
for y in self.recurse(dpath, n):
yield y
else:
if os.path.splitext(x)[1] == '.txt':
with open(dpath) as fp:
for count in range(2):
x += ': ' + fp.readline().replace('\n', '\\n')
elif os.path.splitext(x)[1] == '.zip':
yield (n, x)
n1 = n[:] + [idx == lidx]
# ZipFile in 2.6 doesn't have __enter__/__exit__ yet
zf = ZipFile(dpath)
for info in zf.infolist():
x1 = info.filename
if os.path.splitext(x1)[1] == '.txt':
data = zf.read(x1)
if sys.version_info >= (3,):
data = str(data, encoding='utf-8')
x1 += ': ' + '\\n'.join(data.split(
'\n', 2)[:2]) + '\\n'
yield(n1, x1)
zf.close()
return
yield (n, x)
wt = WalkTree('.' if len(sys.argv) < 2 else sys.argv[1])