900字范文,内容丰富有趣,生活中的好帮手!
900字范文 > python无法打开文件_Python无法打开文件“没有这样的文件或目录”

python无法打开文件_Python无法打开文件“没有这样的文件或目录”

时间:2021-09-10 12:53:48

相关推荐

python无法打开文件_Python无法打开文件“没有这样的文件或目录”

def main():

fh = open('lines.txt')

for line in fh.readlines():

print(line)

if __name__ == "__main__": main()

目录文件

我在for-working.py文件上,正试图访问同一工作目录中的lines.txt文件。但我错了No such file or directory: 'lines.txt'

打开文件时,python需要有一个绝对路径吗?

为什么这条相对路径在这里不起作用?

运行Python3.6

编辑^1我正在运行visualstudio代码和Don Jayamanne的python包扩展,以及“代码运行器”包来编译/执行python代码

编辑^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

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'

编辑^3检查系统路径import sys

print(sys.path)

生成此信息:['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']

编辑^4检查os.getcwd()

跑步import os

print(os.getcwd())

产生c:\www\Ex_Files_Python_3_EssT(1)\Ex_Files_Python_3_EssT\Exercise Files

显然它不在正确的子目录中(需要cd 07 loops文件夹,这样可以缩小问题的范围

编辑^5lines.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

总结

Visual studio代码的代码运行器扩展需要稍加调整才能在子目录中打开文件,因此下面的任何答案都将提供一个更健壮的解决方案,使其独立于IDE的任何扩展/依赖项import os

print(os.getcwd())

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

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。