【问题标题】:python os.listdir no such file or directory [closed]python os.listdir 没有这样的文件或目录
【发布时间】:2019-01-08 10:44:48
【问题描述】:

我知道这对你来说可能听起来很愚蠢,但我现在正在通过互联网上的课程学习 Python,他们要求我们创建一种迷宫。 他们给出了一个“基本代码”,但是当我尝试运行它时,它说 FileNotFoundError: [Errno 2] No such file or directory: 'cartes',错误在 os.listdir(cards )。 我希望代码列出名为 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 ...

【问题讨论】:

  • 下次请在您的帖子正文中包含代码:)
  • 你从哪里运行命令?我想我找到了问题
  • 是的,错误在 os.listdit("cartes")
  • 你能把你代码中的法语单词翻译成英文吗?
  • 现在翻译成英文

标签: python python-3.x file


【解决方案1】:

因为目录是本地的(你没有指定完整的文件路径,例如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))

【讨论】:

  • 感谢您的回答,但人们会评估我的工作,所以我希望它仅通过运行文件(无需在终端中导航)来工作。
  • 检查这个答案stackoverflow.com/questions/28799353/…他们已经解释得比我好
  • 如果我理解,这个“答案”中的错误是当他试图打开文件时(打开(文件名,'r'))。我认为我的错误是“os.listdir()”的路径,而不是“with open()”的路径。我想要做的是使用相对路径(这是你用英语称呼它的方式吗?)来获取文件。 (你看到我的文件夹图片了吗?)
  • 是的,没关系,您只需要从与您感兴趣的文件夹相同的目录中运行脚本即可。您的脚本运行情况如何?
  • 从终端(macOS),我写python3 ...(路径)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-06-17
  • 2021-06-24
相关资源
最近更新 更多