0
import os

def new_directory(directory, filename):
  # Before creating a new directory, check to see if it already exists

  # Create the new file inside of the new directory

  # Return the list of files in the new directory

print(new_directory("PythonPrograms", "script.py"))
Stidgeon
  • 2,622
  • 8
  • 18
  • 27

9 Answers9

1

The os module has a function that abstracts this away called makedirs().

A basic use case will look something like:

import os

# create directory
os.makedirs('new_directory', exist_ok=True)

This will check if the directory exists, and if not will create it.

Robert Kearns
  • 1,468
  • 1
  • 3
  • 15
1

Below would be answer, first check if directory exit or not using isdir() and then create using makedirs(), second create new file inside that directory using open() and finally return list using listdir(),

import os

def new_directory(directory, filename):
  # Before creating a new directory, check to see if it already exists
  if os.path.isdir(directory) == False:
    os.makedirs(directory, exist_ok=True)

  # Create the new file inside of the new directory
  os.chdir(directory)
  with open (filename, "w") as file:
    pass
  os.chdir("..")
  # Return the list of files in the new directory
  return os.listdir(directory)

print(new_directory("PythonPrograms", "script.py"))
Vinod
  • 948
  • 2
  • 13
  • 30
1

Below code is self explanatory

import os
def new_directory(directory, filename):
  # Before creating a new directory, check to see if it already exists
  if os.path.isdir(directory) == False:
    os.mkdir(directory)

  # Create the new file inside of the new directory
  os.chdir(directory)
  with open (filename, "w") as file:
    pass
  os.chdir("..")
  # Return the list of files in the new directory
  return os.listdir(directory)

print(new_directory("PythonPrograms", "script.py"))
Madhan
  • 29
  • 7
0

This should do -

def new_directory(directory, filename):
   os.makedirs(directory, exist_ok=True)
   NewFile = open(str(directory + "//" + filename))
   NewFile.close()
   return(NewFile.name)

Assumptions -

  1. directory is the fully qualified path

  2. filename is just the name

Small note - The returning file list inside the newly created directory sounds little odd when you are creating the only file in there. Functions is returning only file created. You can modify it as required.

Saptarshi
  • 39
  • 1
  • 10
  • doesnot work... i wrote the same but always problem with the return – Abdurraouf Sadi Mar 29 '20 at 05:04
  • What's the problem that you are facing? – Saptarshi Mar 29 '20 at 05:05
  • The new_directory function creates a new directory inside the current working directory, then creates a new empty file inside the new directory, and returns the list of files in that directory. Complete the function to create a file "script.py" in the directory "PythonPrograms". – Abdurraouf Sadi Mar 29 '20 at 05:06
0

Here's a quick untested algorithm to show you how to do it. The other 2 answers are better, but this may show you how to break down the code into parts. Also remember to do a print on any and every variable you have while testing. It really helps a LOT.

    mydir = os.path.expanduser('~')+'/mydir/' # https://stackoverflow.com/questions/40289904
    myfile = 'myfilename.txt'
    def printdir():
        filelist = [ f for f in os.listdir(mydir)] # https://stackoverflow.com/questions/1995373
        print(filelist)
    if os.path.isdir(mydir): # if directory exists
        if os.path.isfile(os.path.join(os.path.sep,mydir,myfile)): # if file exists in directory, just print the file list
            printdir()
        else: # directory exists and file does not
            file = open('myfile.dat', 'w+') # /2967194/
            printdir()
    else: # directory does not exist
        try: # https://stackoverflow.com/questions/273192/
            os.stat(directory)
        except:
            os.mkdir(directory)   
        file = open('myfile.dat', 'w+') # /2967194/
John
  • 89
  • 5
0

this snippet creates the directory if it isn't present already, adds an empty file to the newly created directory and lastly, returns all contents of the directory as list.

import os
def new_directory(directory, filename):
    os.makedirs(directory, exist_ok=True)
    os.chdir(directory)
    with open(filename, 'w') as file:
        file.write("")
    os.chdir("..")
    return(os.listdir(directory))
print(new_directory("PythonPrograms", "script.py"))
  • Hi Anshul. While your code may be helpful to some, an explanation of your code and how it answers the question will mean that your answer is useful to many more users of this fantastic website ;) – Kind Stranger Apr 13 '20 at 20:23
0
import os

def new_directory(directory, filename):
  
  cw = os.getcwd() #notedown current working directory
  # Before creating a new directory, check to see if it already exists
  if os.path.isdir(directory) == False:
    os.mkdir(directory)

  # Create the new file inside of the new directory
  os.chdir(directory)
  with open (filename, "w+") as file:
    pass
  os.chdir(cw) #switch to previous working directory
  ls = os.listdir(directory)

  # Return the list of files in the new directory
  return ls

print(new_directory("PythonPrograms", "script.py"))

The final output will be ['script.py']

Suhas Raj
  • 11
  • 3
  • Note that `os.path.isdir(directory)` will give you `False` even if the file exists but it is not a directory; in that scenario, you will have the `FileExistsError` error and you should manage it; you could either use `if os.path.exists(directory) and os.path.isdir(directory):` or a `Try-Catch`. – ingroxd Aug 20 '20 at 14:26
0
import os

def new_directory(directory, filename):

Before creating a new directory, check to see if it already exists

if os.path.isdir(directory) == False:

os.mkdir(directory)

Create the new file inside of the new directory

os.chdir(directory)

with open (filename,"w") as file:

pass

Return the list of files in the new directory

return os.listdir("../"+directory)

print(new_directory("PythonPrograms", "script.py"))

-1
import os

def new_directory(directory, filename):
  # Before creating a new directory, check to see if it already exists
  if os.path.isdir(directory) == False:
    os.mkdir(directory)

  # Create the new file inside of the new directory
  os.chdir(directory)
  with open (filename, 'w') as file:
    file.write(" ")
    pass
  
  # Return the list of files in the new directory
  return (os.listdir(directory))

print(new_directory("PythonPrograms", "script.py"))