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

2024-06-25 23:27:24 发布

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

我怀疑这是一个非常新的问题,但我找不到任何有帮助的解决方案:( 我一直试图通过构建一个简单的Twitter机器人来开始使用Python,这个机器人会回复在它上面发推的人。它在本地工作,在Heroku上不工作。

一个简单的例子:每次机器人发出tweets时,它都会使用一个名为mainscript.py的脚本,该脚本将最后一条回复的tweet的ID写到一个名为lastid.py的单独文件中。下一次脚本运行时,它将打开lastid.py,对照当前tweets列表检查其中的数字,并且只对那些ID号大于lastid.py中存储的ID号的tweets做出响应。

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

这在当地很管用。运行良好。但是,当我上传到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'  

我绝对100%肯定lastid.py和mainscript.py都在服务器上,并且在同一个目录中——我已经通过在heroku上运行bash三次检查过了。我的.gitignore文件是空的,所以与此无关。

我不明白为什么像“打开同一目录下的文件并读取”这样简单的命令在服务器上不起作用。我到底做错了什么?

(我意识到在尝试用一种新的语言创建自定义之前,我应该先完成一些教程,但现在我已经开始了,我真的很想完成它——任何人能提供的帮助都将非常感谢。)


Tags: 文件py脚本idcloseheroku机器人open
1条回答
网友
1楼 · 发布于 2024-06-25 23:27:24

可能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'

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

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

相关问题 更多 >