Equivalent to python GNU 'cat', which displays unique strings

Has anyone written a GNU cat command in python and would like to share it? The GNU cat really does quite a bit, and I really don't feel like reinventing the wheel today. Yes, I did a search on Google, and after reading too many sad stories about kittens against snakes, I decided to try SO.

Edit: I would like to change it so that it only displays unique lines.

+3
source share
2 answers

It depends on what features you want. If you want to print the file, you can do

with open('myfile') as f:
    for line in f:
        print line,

or to concatenate some files, you can do

filenames = ['file1', 'file2', 'file3']
for filename in filenames:
    with open(filename) as f:
        for line in f:
            print line,

. , , . - , subprocess cat.

, cat, . cat, . , , , - , , , .

+2

: Ned fileinput! :

#!/usr/bin/python

"""cat the file, but only the unique lines
"""
import fileinput

if __name__ == "__main__":
    lines=set()
    for line in fileinput.input():
        if not line in lines:
            print line,
            lines.add(line)

(2010-02-09):

. . .

#!/usr/bin/python
"""cat the file, but only the unique lines
"""
import optparse
import sys

if __name__ == "__main__":
    parser = optparse.OptionParser()
    parser.set_usage('%prog [OPTIONS]')
    parser.set_description('cat a file, only unique lines')

    (options,args) = parser.parse_args()

    lines = set()
    for file in args:
        if file == "-":
            f = sys.stdin
        else:
            f = open(file)
        for line in f:
            if not line in lines:
                print line,
                lines.add(line)
+3

Source: https://habr.com/ru/post/1731923/


All Articles