8.14 python程序框架

上面介绍了如何在python中读写文件,一般python程序都是用来处理文件。下面介绍一下python程序的基本框架。

  • 首先,导入程序需要依赖的木块;

  • 第二,解析选项参数;

  • 第三,读入文件;

  • 第四,通过循环判断进行处理;

  • 第五,将结果写入文件。

    #1 导入模块
      import argparse
      import gzip
      import pathlib
    
    #2解析参数
    parser = argparse.ArgumentParser(
        prog= 'fastq2fasta.py',
        description= 'This Program is used to translate fastq file to fasta file',
        epilog= 'visit our website for more infomation'
    )
    parser.add_argument('-i', '--input', help='input file', required=True)
    parser.add_argument('-o', '--output', help='output', required=True)
    args = parser.parse_args()
    
    #3 读入文件
    file1 = pathlib.Path(args.input)
    if file1.suffix == '.gz':
        f_object = gzip.open(file1, 'rt')
    else:
        f_object = open(file1, 'rt')
    f_output = open(args.output, 'w')
    
    #4 处理数据
    for line in f_object:
        name = line.strip()[1:]
        id = ">" + str(name)
        line2 = f_object.readline()
        line3 = f_object.readline()
        line4 = f_object.readline()
        # print(id)
        # print(line2.strip())
    #5 结果写入文件
        f_output.write(f"{id}\n")
        f_output.write(line2)
    
    f_object.close()
    f_output.close()