gpt4 book ai didi

python - 检查文件是否存在,如果不存在则创建新目录并在目录内创建文件并返回目录内的文件

转载 作者:行者123 更新时间:2023-12-02 00:05:03 26 4
gpt4 key购买 nike

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

最佳答案

下面的代码是不言自明的

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

关于python - 检查文件是否存在,如果不存在则创建新目录并在目录内创建文件并返回目录内的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60910058/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com