【发布时间】:2018-01-20 01:01:44
【问题描述】:
def main():
fh = open('lines.txt')
for line in fh.readlines():
print(line)
if __name__ == "__main__": main()
目录文件
我在for-working.py 文件上,并试图访问同一工作目录中的lines.txt 文件。但我得到错误
没有这样的文件或目录:'lines.txt'
python打开文件需要绝对路径吗?
为什么这个相对路径在这里不起作用?
运行 python 3.6
编辑 ^1 我正在运行 Visualstudio 代码,其中包含 Don Jayamanne 的 python 包扩展,以及“Code Runner”包来编译/执行 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 <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'
EDIT ^3检查 sys.path
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']
EDIT ^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 代码的 Code runner 扩展需要稍微调整以在子目录中打开文件,因此以下任何答案都将提供更强大的解决方案,以独立于 IDE 的任何扩展/依赖项
import os
print(os.getcwd())
对于诊断python解释器看到的当前目录的问题最有用
【问题讨论】:
-
尝试使用
fh = open(os.path.join(os.getcwd(), 'lines.txt')) -
你用的是什么IDE?
-
@GreenSaber
'r'是默认参数,可以省略。 -
import sys; print (sys.path)时看到了什么 -
在这种情况下相关的不是
sys.path,而是os.getcwd()。检查import os; print(os.getcwd())的输出。如果它不是文件夹“07 Loops”的完整路径,则 Python 解释器正在从不同的目录运行。此外,这很愚蠢,但有时会发生,请确保文件“lines.txt”在其名称的开头或结尾没有任何额外的空格或类似的东西。
标签: python python-3.x io compiler-errors