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

2024-09-29 19:20:35 发布

您现在位置:Python中文网/ 问答频道 /正文

首先,我是一个完全初学者,当谈到网络技术,所以这可能是一个相对简单的问题来解决。我试图从与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调用中使用完整文件路径(这是赋值的一部分)。你知道吗


Tags: 文件txt脚本webbinprojectscgiprint
1条回答
网友
1楼 · 发布于 2024-09-29 19:20:35

如果您知道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())

相关问题 更多 >

    热门问题