Python - IOError:[Errno 2]没有这样的文件或目录:u'lastid.py'用于同一目录中的文件.在本地工作,不在Heroku上

Emm*_*a W 5 python heroku

我怀疑这是一个非常新手的问题,但我找不到任何有用的解决方案:(我一直在尝试通过构建一个简单的Twitter机器人来开始使用Python,它回复了发布它的人.它在本地工作,它不适用于Heroku.

快速简介:每次机器人推文时,它都会使用一个名为mainscript.py的脚本,该脚本会将回复的最后一条推文的ID写入名为lastid.py的单独文件中.下一次脚本运行时,它会打开lastid.py,检查当前推文列表中的内部数字,并仅响应ID数大于lastid.py中存储的ID号.

fp = open("lastid.py", 'r')  
last_id_replied = fp.read()
fp.close()

#(snipped - the bot selects the tweet and sends it here...)

fp = open("lastid.py", 'w')
fp.write(str(status.id))
fp.close()
Run Code Online (Sandbox Code Playgroud)

这在当地很有效.运行很好.但是,当我将它上传到Heroku时,我收到此错误:

Traceback (most recent call last):                                                                                                                                 
  File "/app/workspace/mainscript.py", line 60, in <module>                                                                                                        
    fp = open("lastid.py", 'r')                                                                                                                                    
IOError: [Errno 2] No such file or directory: u'lastid.py'  
Run Code Online (Sandbox Code Playgroud)

我绝对100%肯定lastid.py和mainscript.py在服务器上和同一目录内 - 我通过在heroku上运行bash进行三重检查.我的.gitignore文件是空白的,所以它与此无关.

我不明白为什么这样一个简单的命令,如'在同一目录中打开文件并读取它'在服务器上不起作用.我究竟做错了什么?

(我意识到在尝试用新语言构建自定义之前我应该​​已经完成​​了一些教程,但是现在我已经开始了这个我真的很想完成它 - 任何人都能提供的任何帮助都会非常感激.)

Oli*_* W. 5

可能python解释器是从与脚本所在位置不同的目录执行的.

这是相同的设置:

oliver@aldebaran /tmp/junk $ cat test.txt 
a
b
c
baseoliver@aldebaran /tmp/junk $ cat sto.py 
with open('test.txt', 'r') as f:
    for line in f:
        print(line)
baseoliver@aldebaran /tmp/junk $ python sto.py 
a

b

c

baseoliver@aldebaran /tmp/junk $ cd ..
baseoliver@aldebaran /tmp $ python ./junk/sto.py 
Traceback (most recent call last):
  File "./junk/sto.py", line 1, in <module>
    with open('test.txt', 'r') as f:
IOError: [Errno 2] No such file or directory: 'test.txt'
Run Code Online (Sandbox Code Playgroud)

要解决此问题,请导入os并使用绝对路径名:

import os
MYDIR = os.path.dirname(__file__)
with open(os.path.join(MYDIR, 'test.txt')) as f:
    pass
    # and so on
Run Code Online (Sandbox Code Playgroud)