提问人:Younes Abuelayyan 提问时间:11/10/2023 更新时间:11/10/2023 访问量:54
AttributeError:“list”对象没有属性“name”
AttributeError: 'list' object has no attribute 'name'
问:
此代码将我在终端上传递的文件名作为列表而不是字符串
#!/usr/bin/env python3
import argparse
import os
def get_args():
parser = argparse.ArgumentParser(description='get transcript', formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('dna', metavar='FILE', type=argparse.FileType('rt'), nargs='+')
parser.add_argument('-o', '--out_directory', type=str, default='02_rna')
return parser.parse_args()
def main() -> None:
args = get_args()
for dna in args.dna:
content = dna.read()
transcript = content.replace('T', 'U')
file_name = os.path.basename(args.dna.name)
file_processed = file_name.replace('.', '_processed.')
out_directory = os.path.join(args.out_directory, file_processed) if args.out_directory else file_processed
with open(out_directory, 'w') as output_file:
output_file.write(transcript)
print(f'Transcript saved to {out_directory}')
if __name__ == '__main__':
main()
试图把它弄得一团糟,但没有找到解决方案
答:
0赞
Gabriel Ramuglia
11/10/2023
#1
您正在尝试从文件列表(而不是从单个文件)中获取 name 属性。要修复此问题,请在循环中将 args.dna.name 替换为 dna.name。这将访问每个文件对象的 name 属性。
像这样的东西:
def main() -> None:
args = get_args()
for dna in args.dna:
content = dna.read()
transcript = content.replace('T', 'U')
file_name = os.path.basename(dna.name)
base, ext = os.path.splitext(file_name)
file_processed = f"{base}_processed{ext}"
out_directory = os.path.join(args.out_directory, file_processed) if args.out_directory else file_processed
with open(out_directory, 'w') as output_file:
output_file.write(transcript)
print(f'Transcript saved to {out_directory}')
评论