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

- 2,673
- 8
- 20
- 28

- 41
- 1
- 1
- 2
-
given a full `filepath`: `os.makedirs(os.path.dirname(filepath), exist_ok=True)` – william_grisaitis Aug 27 '21 at 00:38
9 Answers
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"))
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.

- 1,631
- 1
- 8
- 15
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"))

- 1,234
- 3
- 21
- 37
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 -
directory is the fully qualified path
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.

- 39
- 1
- 10
-
doesnot work... i wrote the same but always problem with the return – Abdurraouf Sadi Mar 29 '20 at 05:04
-
-
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
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/

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

- 26
- 4
-
1Hi 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
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']

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

- 115
- 1
- 3