在 python 中提取文件并同时重命名

Extract a file and rename it at the same time in python

我想从我的 tarball 文件中提取一个具有特定扩展名的文件,同时给它一个特定的名称。到目前为止,我可以通过扩展名选择我想要的文件并将其解压缩。但是我怎样才能按照我想要的方式重命名呢?

tar = tarfile.open('files/compressed/compressed_file.tar.gz')
for member in tar.getmembers():
    if member.isfile() and member.name.endswith('.nii'):
        f = tar.extract(member, 'files/decompressed/')
    else:
        continue
tar.close()

根据您使用的方法的 docs,返回的文件对象是只读的。这意味着您必须读入数据,然后像往常一样将其写入另一个文件。当你 re-write 文件时,你可以随意命名它:

lines = f.readlines()

with open("your_filename_here.nii", 'w') as output:
    for line in lines:
        output.write(line)

根据文件的格式,您可能需要调整上面的模板。