【问题标题】:Why is the Current Working Directory when accessing a text file not the Directory where my program is saved?为什么访问文本文件时的当前工作目录不是保存我的程序的目录?
【发布时间】:2021-07-11 06:23:29
【问题描述】:

我对 Python 很陌生,并且正在通过一本书学习。我只是想运行 filereader.py,它只是打开并读取一个文本文件。此文本文件与 python 代码位于同一文件夹中。但是当我运行它时,会出现这个错误:

Error:
Exception has occurred: FileNotFoundError
[Errno 2] No such file or directory: 'pi_digits.txt'
  File "C:\Users\lcsan\Desktop\python_work\Chapter 10\filereader.py", line 1, in <module>
    with open('pi_digits.txt') as file_object:

代码如下:

Filereader.py:

with open('pi_digits.txt') as file_object:
    contents = file_object.read()
print(contents)

我尝试导入 os 并使用 os.getcwd() 函数查看程序在哪里搜索文本文件。

这是原始目录:(删减了某些部分) C:\Users\*****\Desktop\python_work\Chapter 10'

这是 os.getcwd() 函数的结果: C:\Users\*****\Desktop\python_work'

它似乎是预期目录后面的一个目录。没有其他方法可以通过相对路径访问它还是我真的必须通过 os.chdir() 指示绝对路径?

【问题讨论】:

    标签: python python-3.x


    【解决方案1】:

    当前目录将是您执行脚本时的当前目录。运行 Python 脚本不会更改目录。如果你需要访问脚本所在目录下的文件,你可以这样做:

    scriptpath = os.path.abspath(os.path.dirname( __file__ ))
    with open(scriptpath + '/pi_digits.txt') as file_object:
    

    【讨论】:

      【解决方案2】:

      我不确定,但如果您通过终端运行代码,您的终端工作目录应该与代码目录相同。

      如果代码的路径 dir1/dir2/code.py

      目录中的文件:

      code.py s

      sample.txt

      sample.txt 内容

      text
      text
      text
      text
      this is a sample text
      

      代码:

      import os
      print(os.getcwd())
      lines = open("sample.txt")
      print(lines.read())
      

      从顶级目录运行时:

      C:\Users\User\Documents\dir1
      Traceback (most recent call last):
        File "dir2/code.py", line 3, in <module>
          lines = open("sample.txt")
      FileNotFoundError: [Errno 2] No such file or directory: 'sample.txt'
      

      从同一目录运行时:

      C:\Users\User\Documents\dir1\dir2>python code.py
      C:\Users\User\Documents\dir1\dir2
      text
      text
      text
      text
      this is a sample text
      

      【讨论】:

        猜你喜欢
        • 2023-03-23
        • 2022-01-21
        • 1970-01-01
        • 2019-09-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多