有没有更好的方法来透明地读取和写入常规/gzip文件或stdin/stdout?

2024-05-14 12:34:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我想编写一些代码,从文件(regular/gzip)或stdin读取数据,然后写入文件(regular/gzip)或stdout。这个问题的最佳解决方案是什么

到目前为止,我的解决方案如下所示:

# 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)

你觉得怎么样?什么是更好的更通用的解决方案


Tags: inputoutputaswithlineargsopen解决方案
1条回答
网友
1楼 · 发布于 2024-05-14 12:34:58
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()

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)

相关问题 更多 >

    热门问题