首先,我是一个完全初学者,当谈到网络技术,所以这可能是一个相对简单的问题来解决。我试图从与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代码工作得很好,因为如果我直接从python文件中打印msgs.txt
的内容(即删除python代码的最后两行并用print("alice: hello\nbob: whatever")
替换它们),它会很顺利。我的主要问题是试图访问那个文件。就像python脚本在我试图从网页打开它时都看不到一样。你知道吗
任何建议都将不胜感激。提前谢谢!你知道吗
编辑:不允许在open
调用中使用完整文件路径(这是赋值的一部分)。你知道吗
如果您知道
msgs.txt
将与p3.py
位于同一目录中,您可以查询__file__
的目录部分。你知道吗试试这个:
相关问题 更多 >
编程相关推荐