python - 带有新空文件的 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']
解决方案
请尝试下面的代码,它对我来说很好。首先它检查目录是否已经存在,然后创建文件,并列出目录。
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")
推荐阅读
- mysql - 使用 show create 功能失去与服务器的连接
- regex - 将文件内容与模式/正则表达式匹配(编辑后重新发布)
- javascript - 使用 puppeteer 按文本选择
- android - 不同尺寸的尺寸
- javascript - 如何在postgres中查询过去四个星期的每周总和
- typescript - Vue.js + Typescript:为什么 v-model 不被识别为值?
- javascript - 如何使用 Scss 导入媒体查询?
- sqlalchemy - SQLAlchemy 基于用户输入构建过滤条件
- sql - SQL Server 中的完全递归员工-老板关系
- apache-kafka - kafka-connect 文件脉冲连接器独立无法启动(偏移管理器上找不到类异常)