Python 尝试打开文本文件时脚本抛出非常奇怪的错误

Python script throwing very odd error when trying to open a text file

首先,在网络技术方面我完全是初学者,所以这可能是一个相对容易解决的问题。我试图从与 XMLHTTPRequest 交互的 python 脚本打开文本文件,但收到以下错误:

Traceback (most recent call last):
File "/home/ryan/VirtualDesktop/ComputerScience/4410_web_Technologies/projects/p3stuff/cgi-bin/p3.py", line 20, in <module>
msgs = open("msgs.txt")
FileNotFoundError: [Errno 2] No such file or directory: 'msgs.txt'

这是 python 代码:

#!/usr/bin/python3

import sys, cgi
import cgitb

cgitb.enable()
sys.stderr = sys.stdout

print("Access-Control-Allow-Origin: *")
print("Content-type: text/html\n\n")

msgs = open("msgs.txt")
print(msgs.read())

"msgs.txt" 文件肯定在正确的目录中,如果我 运行 终端中的 python 脚本(不与 javascript):

ryan@ryan-XPS-15-9560:~/VirtualDesktop/ComputerScience/4410_web_Technologies/projects/p3stuff/cgi-bin$ ls
msgs.txt  p3.py*
ryan@ryan-XPS-15-9560:~/VirtualDesktop/ComputerScience/4410_web_Technologies/projects/p3stuff/cgi-bin$ ./p3.py 
Access-Control-Allow-Origin: *
Content-type: text/html

alice: hello
bob: whatever

ryan@ryan-XPS-15-9560:~/VirtualDesktop/ComputerScience/4410_web_Technologies/projects/p3stuff/cgi-bin$ 

在我看来,我用来与 python 脚本交互的 javascript 代码工作正常,因为如果我只打印 msgs.txt 的内容,它会很顺利直接从 python 文件(即删除 python 代码的最后两行并将其替换为 print("alice: hello\nbob: whatever")。只是试图访问该文件似乎是我的主要问题。就像python 当我试图从我的网页打开它时,脚本甚至看不到它。

如有任何建议,我们将不胜感激。提前致谢!

编辑:不允许在 open 调用中使用完整文件路径(这是分配的一部分)。

如果知道msgs.txt会和p3.py在同一个目录下,可以查询__file__.

的目录部分

试试这个:

import os

def filename(x):
    return os.path.join(os.path.dirname(os.path.realpath(__file__)), x)

with open(filename('msgs.txt')) as msgs:
    print(msgs.read())