【问题标题】:How to correctly put in the C Drive correctly in PythonPython中如何正确正确放入C盘
【发布时间】:2023-02-22 02:10:49
【问题描述】:

我正在尝试将 C 驱动器插入 Python,但我一直收到此错误。

解决此解决方案的最佳方法是什么。

我尝试手动将其放入并使用 ^Z 功能进行设置,但它不起作用。我知道它可以在命令提示符下运行,但在 Python 3 中不起作用。我正在尝试使用它来打开 txt 文件。

【问题讨论】:

  • 这看起来像是在 Python 解释器中输入 shell 命令的错误尝试。

标签: python file path drive


【解决方案1】:

看起来您缺少“:”。

import os
# This will create a text document "test.txt" in a folder called "temp" that is stored in the root directory of the C: drive.
with open(os.path.join("C:", os.sep, "temp", "tester.txt"), "w") as testdoc:
    testdoc.write("This is a test.")

您需要额外的 os.sep 否则 python 将无法正确识别文件结构。您也可以只使用“C:\”。

请注意,根据您尝试访问的文件所在的位置,您可能需要在提升的终端中(在管理员模式下打开命令提示符)。

编辑:正如@chepner 指出的那样,您的示例图像显示了粘贴到 python 解释器中的文件结构。您至少需要在它周围加上引号才能将其视为文件路径字符串。但目前尚不清楚您要在这里完成什么,因此需要更多详细信息来提供帮助。

如果你想打开一个文件,你可以在 python 中使用...

import os
with open(os.path.join("C:", os.sep, "Users", "User", "Desktop", "py4e", "filename.txt"), 'r') as file:
    # Do stuff with file, like file.readlines()

【讨论】:

  • 你看过问题中的图片了吗?这似乎根本没有关系。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-08-04
  • 1970-01-01
  • 1970-01-01
  • 2017-12-21
  • 2011-10-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多