'Extract ID from multiple fasta file and save in seperate text file with existing name using python

I am having multiple fasta file with extension .fna, I want to extract Id only and save in multiple text file respectively, how it can be done using python, File look like this, image is attached hereenter image description here I tried this code , but getting error,

import os
import pathlib # to remove file extension
for x in os.listdir():
   file_name = pathlib.Path(x) # to remove extension
   file_name_wo_ext = file_name.stem # to remove extension
   print(file_name_wo_ext)
   with open("%s.txt" % file_name_wo_ext, "w") as f: # name each consecutive file name as .txt 
      for y in open(x, "r"):
        if '>' in y:
            z=y.replace(">","") # remove > from id 
            print(z)
            f.write(z)


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source