【问题标题】:Can't open file in the same directory无法在同一目录中打开文件
【发布时间】:2022-01-07 12:20:35
【问题描述】:

我正在关注有关文件的 python 教程,但我无法在与 python 脚本相同的目录中打开文本文件。这有什么原因吗?

f = open("test.txt", "r")

print(f.name)

f.close()

错误信息:

Traceback (most recent call last):
  File "c:\Users\07gas\OneDrive\Documents\pyFileTest\ManipulatingFiles.py", line 1, in <module>
    f = open("test.txt", "r")
FileNotFoundError: [Errno 2] No such file or directory: 'test.txt'

Here's a screenshot of proof of it being in the same directory:

【问题讨论】:

  • 你是从同一个目录执行的吗?
  • 它告诉你test.txt 不在当前工作目录中。我们不知道那是什么。你是如何运行代码的,环境选项有哪些?
  • 他们在同一个文件夹中查看屏幕截图
  • 你是如何运行python脚本的?
  • 修复错字后出现此错误:File "c:\Users\07gas\OneDrive\Documents\pyFileTest\ManipulatingFiles.py", line 3, in &lt;module&gt; f = open(os.path.abspath("test.txt"), "r") FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Users\\07gas\\test.txt'

标签: python file directory


【解决方案1】:

问题是"test.txt" 是一个相对文件路径,将相对于脚本运行时的当前工作目录 (CWD) 进行解释。一种简单的解决方案是使用预定义的__file__ 模块属性,它是当前运行脚本的路径名,以获取脚本文件所在的(又名“父”)目录,并使用该属性来获取数据文件中的绝对文件路径同一个文件夹。

您还应该使用with 语句来确保文件自动关闭。

下面的代码展示了如何做这两件事:

from pathlib import Path

filepath = Path(__file__).parent / "test.txt"

with open(filepath, "r") as f:
    print(f.name)

【讨论】:

    猜你喜欢
    • 2021-05-20
    • 2023-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多