Python - IOError: [Errno 2] No such file or directory: u'lastid.py' for file in same directory. Works locally, doesn't on Heroku

后端 未结 1 624
一个人的身影
一个人的身影 2021-01-18 22:47

I suspect this is a very newbie question but I can\'t find any solutions that are helping :( I\'ve been trying to get started with Python by building a simple Twitter bot w

1条回答
  •  梦毁少年i
    2021-01-18 23:25

    Probably the python interpreter is being executed from a different directory than where your script lives.

    Here's the same setup:

    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 
        with open('test.txt', 'r') as f:
    IOError: [Errno 2] No such file or directory: 'test.txt'
    

    To solve this, import os and use absolute pathnames:

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

    0 讨论(0)
提交回复
热议问题