【问题标题】:Python script throwing very odd error when trying to open a text file尝试打开文本文件时 Python 脚本抛出非常奇怪的错误
【发布时间】:2018-08-22 10:02:47
【问题描述】:

首先,我是网络技术的初学者,所以这可能是一个相对简单的问题要解决。我正在尝试从与 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 调用中使用完整的文件路径(这是分配的一部分)。

【问题讨论】:

  • 您是否考虑过“正确目录”(很可能是您的主目录Pythonos.getcwd() )),在某些情况下可能会发生变化(例如,从外部工具运行时)?如果指定完整路径会发生什么?
  • 尝试添加文件的完整路径。例如; open("c:\folder\msgs.txt")
  • open() 的使用方式是指相对路径。如果您从该目录之外的任何位置执行 p3.py,您将遇到错误。
  • 如果 "msgs.txt" in os.listdir(os.getcwd()) 不是 True,请将工作目录更改为文件所在的位置(使用 os.chdir(...))或指定完整路径,就像 anonyXmous 提到的那样。
  • 添加完整路径确实有效!我感谢大家的建议。我现在面临的唯一问题是这是一个类的项目,我们被明确告知不要使用完整的文件路径,因为我们的教授将在他的本地机器上运行它,并且保证我们的文件路径会有所不同。有没有一种快速的方法可以在运行时获取完整的文件路径并偶然使用它?

标签: javascript python html xmlhttprequest cgi


【解决方案1】:

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

【讨论】:

  • 大声告诉你。非常感谢,这正是我所需要的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-12
  • 1970-01-01
  • 1970-01-01
  • 2020-05-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多