Python无法打开文件"没有这样的文件或目录"

Vin*_*ang 3 python io compiler-errors python-3.x

def main():
    fh = open('lines.txt')
    for line in fh.readlines():
        print(line)

if __name__ == "__main__": main()
Run Code Online (Sandbox Code Playgroud)

目录文件

在此输入图像描述

我在for-working.py档案,我正在尝试访问lines.txt同一工作目录中的文件.但我得到错误

没有这样的文件或目录:'lines.txt'

打开文件时python是否需要有绝对路径?

为什么这条相对路径不适用于此?

运行python 3.6

编辑^ 1我正在运行带有Don Jayamanne的python包扩展的visualstudio代码,以及用于编译/执行python代码的"Code Runner"包

编辑^ 2完整的错误:

Traceback (most recent call last):
  File "c:\www\Ex_Files_Python_3_EssT(1)\Ex_Files_Python_3_EssT\Exercise Files\07 Loops\for-working.py", line 11, in <module>
    if __name__ == "__main__": main()
  File "c:\www\Ex_Files_Python_3_EssT(1)\Ex_Files_Python_3_EssT\Exercise Files\07 Loops\for-working.py", line 7, in main
    fh = open('lines.txt', 'r')
FileNotFoundError: [Errno 2] No such file or directory: 'lines.txt'
Run Code Online (Sandbox Code Playgroud)

编辑^ 3检查sys.path

import sys
print(sys.path)
Run Code Online (Sandbox Code Playgroud)

产生这些信息:

['c:\\www\\Ex_Files_Python_3_EssT(1)\\Ex_Files_Python_3_EssT\\Exercise Files\\07 Loops', 
'C:\\Users\\Kagerjay\\AppData\\Local\\Programs\\Python\\Python36\\python36.zip', 'C:\\Users\\Kagerjay\\AppData\\Local\\Programs\\Python\\Python36\\DLLs', 'C:\\Users\\Kagerjay\\AppData\\Local\\Programs\\Python\\Python36\\lib', 'C:\\Users\\Kagerjay\\AppData\\Local\\Programs\\Python\\Python36', 'C:\\Users\\Kagerjay\\AppData\\Local\\Programs\\Python\\Python36\\lib\\site-packages']
Run Code Online (Sandbox Code Playgroud)

编辑^ 4检查os.getcwd()

运行

import os
print(os.getcwd())
Run Code Online (Sandbox Code Playgroud)

产生

c:\www\Ex_Files_Python_3_EssT(1)\Ex_Files_Python_3_EssT\Exercise Files
Run Code Online (Sandbox Code Playgroud)

那么它肯定不在正确的子目录中(需要cd 07 loops文件夹,这会缩小问题范围

编辑^ 5 lines.txt文件中的内容

我正在打开的lines.txt文件看起来像这样.开始时没有额外的空格或任何内容

01 This is a line of text
02 This is a line of text
03 This is a line of text
04 This is a line of text
05 This is a line of text
Run Code Online (Sandbox Code Playgroud)

综上所述

Visual Studio代码的Code runner扩展需要稍微调整以打开子目录中的文件,因此以下任何答案都将提供更强大的解决方案,以独立于IDE的任何扩展/依赖性

import os
print(os.getcwd())
Run Code Online (Sandbox Code Playgroud)

对python解释器看到的当前目录诊断问题最有用

tha*_*vik 5

获取文件的目录,并将其与要打开的文件一起加入:

def main():
    dir_path = os.path.dirname(os.path.realpath(__file__))
    lines = os.path.join(dir_path, "lines.txt")
    fh = open(lines)
    for line in fh.readlines():
        print(line)

if __name__ == "__main__": main()
Run Code Online (Sandbox Code Playgroud)