0

我正在运行的程序需要识别导入的文件是否为 gzip 压缩文件。这些文件是使用 argparse 进来的:

parser.add_argument('file_sources', nargs='*', type=argparse.FileType('r'), default=sys.stdin, help='Accepts one or more fasta files, no arguments defaults to stdin')
options = parser.parse_args()
open_files = options.file_sources

并存储在一个列表中,程序在该列表中循环并根据文件 ext 确定该文件是否被压缩.gz

open_files = options.file_sources
#if there is nothing in the list, then read from stdin
if not open_files:
    open_files = [sys.stdin]
#if there are files present in argparse then read their extentions
else:
    opened_files = []
    for _file in open_files:
        if _file.endswith(".gz"):
            _fh = gzip.open(_file,'r')
            opened_files.append(_fh)
        else:
            _fh = open(_file,'r')
            opened_files.append(_fh)

代码中断_file.endswith(".gz"):,给出错误'file' has no attribute 'endswith。如果我删除 argparse 类型,_file 将从文件对象变为字符串。这样做会endwith()起作用,但现在该文件只是一个带有其名称的字符串。

如何在解释文件扩展名的同时保留文件的功能(并且不必像这样使用绝对路径,os.path.splitext因为我只是从程序的当前目录中获取文件)?

4

1 回答 1

1

file没有属性endswith,但是string有,所以:

改变:

if _file.endswith(".gz"):

到:

if _file.name.endswith(".gz"):

并且因为 _file 是一种文件类型,open所以像这样使用:

_fh = gzip.open(_file.name,'r')
于 2014-11-07T11:04:41.237 回答