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 我正在使用 Don Jayamanne 的 python 包扩展运行 visualstudio 代码,并使用“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'
编辑 ^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']
编辑 ^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
文件夹,这缩小了问题范围
编辑 ^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
总之
Visual Studio 代码的代码运行程序扩展需要稍微调整以打开子目录中的文件,因此以下任何答案都将提供更强大的解决方案,以独立于 IDE 的任何扩展/依赖项
import os
print(os.getcwd())
对于诊断 python 解释器看到的当前目录的问题最有用
原文由 Vincent Tang 发布,翻译遵循 CC BY-SA 4.0 许可协议
获取文件的目录,并将其与要打开的文件连接起来: