Bird
0
0

You want to create a new directory named 'backup' only if it does not exist. Which code snippet correctly does this?

hard📝 Application Q8 of 15
Python - Standard Library Usage
You want to create a new directory named 'backup' only if it does not exist. Which code snippet correctly does this?
Aimport os os.mkdir('backup')
Bimport os if not os.path.exists('backup'): os.mkdir('backup')
Cimport os os.makedirs('backup')
Dimport os os.mkdir('backup') os.mkdir('backup')
Step-by-Step Solution
Solution:
  1. Step 1: Understand directory creation

    os.mkdir() creates a directory but raises error if it exists.
  2. Step 2: Check existence before creating

    Using os.path.exists() to check prevents error by creating only if missing.
  3. Step 3: Analyze other options

    os.makedirs() can create nested dirs but without check may error; calling mkdir twice causes error.
  4. Final Answer:

    Check existence then mkdir -> Option B
  5. Quick Check:

    Check before mkdir to avoid errors [OK]
Quick Trick: Check if folder exists before mkdir to avoid errors [OK]
Common Mistakes:
  • Calling mkdir twice
  • Not checking existence
  • Confusing makedirs with mkdir

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes