python操作系统列表目录没有这样的文件或目录

2024-06-03 07:22:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我知道这听起来可能很蠢,但我现在正在学习Python,通过在互联网上学习课程,他们要求我们创建一种迷宫。 它们给出了一个“基本代码”,但当我试图运行它时,它显示FileNotFoundError:[Errno 2]没有这样的文件或目录:“cartes”,错误在操作系统列表目录(卡片)。 我希望代码列出名为cartes的本地目录的内容,但无法这样做,因为我收到FileNotFoundError。在

这是我正在努力解决的代码:

# -*-coding:Utf-8 -*

"""This file contains the main code of the game.

Run him with Python to start the game.

"""

import os

from map import Map

# We load the existing maps
maps = []
for file_name in os.listdir("maps"):
    if file_name.endswith(".txt"):
        path = os.path.join("maps", nom_fichier)
        map_name = file_name[:-3].lower()
        with open(path, "r") as file:
            content = file.read()
            # Map creation, to complete

# We display the existing maps
print("Existing labyrinths :")
for i, map in enumerate(maps):
    print("  {} - {}".format(i + 1, map.nom))

# If there is a saved game, we display it, to complete

# ... Complete the program ...

Tags: thetopath代码nameimport目录game
1条回答
网友
1楼 · 发布于 2024-06-03 07:22:54

因为该目录是本地的(您没有指定整个文件路径,例如C:\Users....\roboc如果该文件夹在同一个目录中运行,脚本只能找到它。在

打开终端并导航到roboc文件夹。然后运行python roboc.py,这应该可以提供一个快速修复:)

或者试试这个

import os

from map import Map

# We load the existing maps
maps = []
script_path = os.path.dirname(os.path.realpath(__file__))
maps_path = os.path.join(script_path, "maps")
for file_name in os.listdir(maps_path):
    if file_name.endswith(".txt"):
        path = os.path.join(maps_path, nom_fichier)
        map_name = file_name[:-3].lower()
        with open(path, "r") as file:
            content = file.read()
            # Map creation, to complete

# We display the existing maps
print("Existing labyrinths :")
for i, map in enumerate(maps):
    print("  {} - {}".format(i + 1, map.nom))

相关问题 更多 >