【问题标题】:Why is relative path not working in python 3? [duplicate]为什么相对路径在 python 3 中不起作用? [复制]
【发布时间】:2021-04-12 08:43:02
【问题描述】:

我无法在 python3 中获得相对路径来工作 我以前用过 但是现在当我尝试读取同一文件夹(目录)中的文本文件时 它显示

Traceback (most recent call last):
  File "F:\python project\main_programm\main.py", line 1, in <module>
    open("text.txt")
FileNotFoundError: [Errno 2] No such file or directory: 'text.txt'

代码只是

open("text.txt")

我不知道它为什么这样做 该目录有 main.py 和 text.txt (自动完成工作!)

所以我在网上搜索 并找到了一个os命令来查找工作目录

import os
print(os.getcwd())

我明白了

G:\PyCharm Community Edition 2020.3.1\jbr\bin

当我通过 terminal(cmd) 运行这个确切的代码时 和 蟒蛇"F:\python project\main_programm\main.py" 我得到C:\Users\$my_user_name$

【问题讨论】:

  • 你是如何执行你的程序的?
  • @khelwood 是通过 pycharm
  • @khelwood 但是当我通过终端(cmd)运行时我重新编辑了我的问题
  • 如果你通过终端执行它,那么在运行脚本之前cd 到你想要的任何目录。

标签: python python-3.x path filepath


【解决方案1】:

也许这对你有帮助:

file = open('txt.txt')
content = file.read()
file.close()

【讨论】:

  • 哥们有什么问题我看到我的导师使用了这个代码,但在我的机器上它不起作用:(
  • 您在左上角目录中看到您的 .txt 文件了吗? (在 pycharm 本身中)
猜你喜欢
  • 2016-11-08
  • 2014-10-08
  • 2013-03-21
  • 2018-01-27
  • 1970-01-01
  • 2012-03-10
  • 1970-01-01
  • 2017-07-12
  • 1970-01-01
相关资源
最近更新 更多