FileExistsError: [WinError 183] Unable to create a file that already exists

2

once the directory is created, when executing the code it gives the following error: How can I do so if that directory already exists, the function continues writing the file

FileExistsError Traceback (most recent call last)  in ()       1

---- > 2 fetch_genome ("X51500.1", "genseqs")

in fetch_genome (genome_id, directory)       9 url_template=" link "

10

--- > 11 os.mkdir (directory)

12

13 genome_id = genome_id.strip ()

FileExistsError: [WinError 183] Unable to create a file that already exists: 'genseqs'

import requests
import os
import sys
import time

def fetch_genome(genome_id, directory):

       url_template = "http://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?db=nucleotide&id=%s&rettype=fasta&retmode=text"

       os.mkdir(directory)

       genome_id = genome_id.strip()

       print("Fetching ", genome_id, "...")

       out_file = os.path.join(directory, genome_id + ".fa")
       if os.path.exists(out_file):
            print("already fetched")

       resp = requests.get(url_template % genome_id)
       open(out_file, "w").write(resp.text)
       print("Done")
       return True
    
asked by roberto 04.11.2017 в 19:07
source

1 answer

0

Indeed os.mkdir throws an exception if the directory already exists:

  

If the directory already exists, FileExistsError is raised.

You have several possibilities, among them:

  • Using os.mkdir but capturing the exception (also valid for Python 2.x):

    try: 
        os.makedirs(directory)
    
    except OSError:
        if not os.path.isdir(directory):
            raise
    
  • Using os.mkdirs with the exist_ok=True parameter:

    os.makedirs(directory, exist_ok=True)
    
  • Use the pathlib (Python> = 3.5) library:

    import pathlib
    pathlib.Path(directory).mkdir(parents=True, exist_ok=True) 
    

    Although the method already existed in Python 3.4 the parameter exist_ok was not introduced until version 3.5.

answered by 04.11.2017 / 19:19
source