This is a test version of Biostars. For the public version, visit https://www.biostars.org.
Convert all fasta files in one folder

Dear colleagues,

Could you please help to finish my code:

I take each file in the certain one folder and make from .fna file .json so that the name of .fna become the same name but as .json , in the same folder.

for example, was:

GCF_000783815.1_ASM78381v1_genomic.fna

become:

GCF_000783815.1_ASM78381v1_genomic.json
from Bio import SeqIO
import json
my_dict = {}
import os
_file = os.listdir("data/")
print(_file)
for EL in _file:
    with open(EL, 'r') as new_fasta:
        for x in SeqIO.parse(new_fasta, 'fasta'):
            my_dict = {
                "dataset": x.id,
                "sequence": str(x.seq)
            }
    with open('my_dict????.json', 'w') as f:
        json.dump(my_dict???, f)
fasta json

thks, but I'm in Win working, could you pls advise if knows for this part:

with open('my_dict????.json', 'w') as f: json.dump(my_dict???, f)

@ Buffo It is not as simple as that. From python code, OP intention seems to generate a dictionary from id and sequence and then dump dictionary as json. Only part that has some problem is last two lines in python code. Appending items to dictionary is also confusing.

This is a xy problem. OP needs to clarify the objective of the python code and expected output.

1 answer

Something like this, should create a json file for each fna file with the same base name. The json file will contain one json object per line:

import json

from Bio import SeqIO
from pathlib import Path

data_dir = Path("data")

for fasta in data_dir.glob("*.fna"):
    with Path(data_dir / f"{fasta.stem}.json").open(mode="w") as f:
        for record in SeqIO.parse(fasta, "fasta"):
            data = {
                "dataset": record.id,
                "sequence": str(record.seq)
            }
            f.write(json.dumps(data))

thanks for advise, previous post was concerning making the json from fasta via dict, and in this one problem was to make these .fna files for json in the same folder

Log in to answer this question.