简体   繁体   English

有没有更好的方法可以透明地从常规/ gzip文件或标准输入/标准输出中读写?

[英]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. 我想编写一些从文件(常规/ gzip)或stdin读取并写入文件(常规/ gzip)或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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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