提问者:小点点

找不到文件目录错误。请帮助。FileNotFoundError:[错误号2]没有这样的文件或目录:“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) as file:
                    pass

            # Return the list of files in the new directory
            return os.listdir(directory)

            print(new_directory("PythonPrograms", "script.py"))

显示此错误的代码“fileNotfounderror:[errno2]没有这样的文件或目录:'script.py'”


共1个答案

匿名用户

open函数中缺少模式

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, mode="w+") as file:
        pass

    # Return the list of files in the new directory
    return os.listdir(directory)

print(new_directory("PythonPrograms", "script.py"))