LeannM
LeannM

Reputation: 1

Multiple dictionaries from multiple files

I am a beginner in Python and am trying to get Python to read multiple files and make a dictionary for each one. I have made a function to read one file and make that into a dictionary, but when I try to apply to it multiple files it tells me there is no such file or directory even though I thought I have provided it. I am trying to get it to make a dictionary from all the files is the folder. Here is my code.

from typing import Dict

gene_region = '>'

def parse_sequences(filename) -> Dict[str, str]:

    result = {}

    last_name = None
    with open(filename) as sequences:
        for line in sequences:
            if line.startswith(gene_region):
                last_name = line[1:-1]
                result[last_name] = []
            else:
                result[last_name].append(line[:-1])

    for name in result:
        result[name] = ''.join(result[name])

    return result

import os

dirname = str(input('Please enter the folder directory:'))

for filename in os.listdir(dirname):

     parse_sequences(filename)```

Here is the error it gives me:

FileNotFoundError
Traceback (most recent call last)
<ipython-input-1-19ae3209a521> in <module>
     34 for filename in os.listdir(dirname):
     35
---> 36      parse_sequences(filename)

<ipython-input-1-19ae3209a521> in parse_sequences(filename)
      9
     10     last_name = None
---> 11     with open(filename) as sequences:
     12         for line in sequences:
     13             if line.startswith(gene_region):

FileNotFoundError: [Errno 2] No such file or directory: '3163_3.fa'

Upvotes: 0

Views: 358

Answers (1)

Grismar
Grismar

Reputation: 31396

os.listdir(dir) only returns the filenames of the files in dirname, not the entire path, so if you list gene_files and it contains example.dat, it will return example.dat, not gene_files/example.dat, which is what you need. You can just add the filename to the path:

for filename in os.listdir(dirname):
     parse_sequences(os.path.join(dirname, filename))

Upvotes: 1

Related Questions