首页 > 解决方案 > 带有新空文件的 NewDirectory

问题描述

块引用

new_directory 函数在当前工作目录中创建一个新目录,然后在新目录中创建一个新的空文件,并返回该目录中的文件列表。完成在“PythonPrograms”目录中创建文件“script.py”的功能。

import os

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



   return os.listdir(os.path.join(directory,filename))
  # Create the new file inside of the new directory

  # Return the list of files in the new directory
 print(new_directory("PythonPrograms", "script.py"))


 output should be:
 ['script.py']

标签: pythonpython-3.xdirectory

解决方案


请尝试下面的代码,它对我来说很好。首先它检查目录是否已经存在,然后创建文件,并列出目录。

import os

def createDir(dirname, filename):
    filepath = os.path.join(dirname, filename)
    if not os.path.exists(dirname):
        os.makedirs(dirname)
        f = open(filepath, "a")
        f.close()
        print("Directory and File created Successfully")
        print(os.listdir(dirname))
    else:
        print("Directory Already Exist")

createDir("PythonPrograms", "script.py")

推荐阅读