Search code examples
javascriptpythonhtmlxmlhttprequestcgi

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


First off, I am a total beginner when it comes to web tech, so this may be a relatively simple problem to solve. I am attempting to open a text file from a python script that is interacting with an XMLHTTPRequest and I am receiving the following error:

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'

This is the python code:

#!/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())

The "msgs.txt" file is definitely in the proper directory and it runs fine if I run the python script in my terminal (without interacting with the 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$ 

It seems to me the javascript code that I am using to interact with the python script is working fine, as it goes smoothly if I just print the contents of msgs.txt straight from the python file (ie removing the last two lines of the python code and replacing them with print("alice: hello\nbob: whatever"). Just trying to access that file seems to be my main problem. It's like the python script can't even see it when I'm trying to open it from my webpage.

Any advice would be much appreciated. Thank you in advance!

Edit: Using the full filepath in the open call is not permitted (this is part of an assignment).


Solution

  • If you know that msgs.txt will be in the same directory as p3.py, you can query the directory portion of __file__.

    Try this:

    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())