3
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")) 
1
  • given a full filepath: os.makedirs(os.path.dirname(filepath), exist_ok=True) Commented Aug 27, 2021 at 0:38

9 Answers 9

5

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")) 
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

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

Comments

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/ 

Comments

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.

3 Comments

doesnot work... i wrote the same but always problem with the return
What's the problem that you are facing?
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".
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")) 

1 Comment

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

1 Comment

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

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.