Abdurraouf Sadi
Abdurraouf Sadi

Reputation: 51

check if the file exist if not create new dir and create file inside the dir and return the file inside the dir

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"))

Upvotes: 3

Views: 16745

Answers (9)

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"))

Upvotes: 0

user14196479
user14196479

Reputation:

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"))

Upvotes: 5

Suhas Raj
Suhas Raj

Reputation: 21

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']

Upvotes: 0

AKinsoji Hammed Adisa
AKinsoji Hammed Adisa

Reputation: 115

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"))

Upvotes: -1

Vinod
Vinod

Reputation: 1290

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"))

Upvotes: 1

Anshul Chaudhary
Anshul Chaudhary

Reputation: 26

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"))

Upvotes: 0

Saptarshi
Saptarshi

Reputation: 39

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.

Upvotes: 0

John
John

Reputation: 222

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/

Upvotes: 0

Robert Kearns
Robert Kearns

Reputation: 1706

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.

Upvotes: 1

Related Questions