简体   繁体   中英

Is there a better way to transparently read and write from regular/gzip file or stdin/stdout?

I want to write some code which reads from either a file (regular/gzip) or stdin and writes to either a file (regular/gzip) or stdout. What is for you the best solution to this problem?

My solution looks like this so far:

# read input
if not args.input:
    outlines = process_lines(sys.stdin, args)

elif args.input.endswith(".gz"):
    with gzip.open(args.input, "r") as infile:
        outlines = process_lines(infile, args)

else:
    with open(args.input, "r") as infile:
        outlines = process_lines(infile, args)

# write output
if not args.output:
    for line in outlines:
        sys.stdout.write("%s\n" % line)

elif args.output.endswith(".gz"):
    with gzip.open(args.output, "w") as outfile:
        for line in outlines:
            outfile.write("%s\n" % line)

else:
    with open(args.output, "w") as outfile:
        for line in outlines:
            outfile.write("%s\n" % line)

What do you think? What would be a better more generic solution?

infile = sys.stdin
# read input
if args.input:
    if args.input.endswith(".gz"):
        infile =  gzip.open(args.input, "r")
    else:
        infile open(args.input, "r")
outlines = process_lines(infile, args)
if infile != sys.stdin:
    infile.close()
outfile = sys.stdout
# write output 
if args.output:
    if args.output.endswith(".gz"):
        outfile = gzip.open(args.output, "w")
    else:
        outfile = 
open(args.output, "w")
for line in outlines:
    outfile.write("%s\n" % line)
if outfile != sys.stdout:
    outfile.close()

or

def open_file(file_path: str, mode: str):
    if file_path.endswith(".gz"):
        return gzip.open(file_path, mode)
    else:
        return open(file_path, mode)

def save_result(fp, outlines):
    for line in outlines:
        outfile.write("%s\n" % line)

if not args.input:
    outlines = process_lines(sys.stdin, args)
else:
    with open_file(args.input, "r") as infile:
        outlines = process_lines(args.input, args)
if not args.output:
    save_result(sys.stdout, outlines)
else:
    with open_file(args.output, "w") as outfile:
        save_result(outfile, outlines)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM