Script cant write .txt file. Pythonanywhere

Viewed 133

I have a simple script for yandex.metrika counters goals logging. It writes when goal was created or deleted to txt file. Code for writing to text file:

if cID == 18662179:
     with open('toyota_goalss_log.txt','a') as log2:
         print(str(datetime.date.today()) +str(res2), file = log2)
         print(str(datetime.date.today()) +str(res2),cID)
         log2.close()

The script runs correctly if I click the button "run" in editor on pythonanywhere: No errors, the data is appended to the text files. But if I create a task to run this script every hour the data does not get appended to the text files... and there are no errors in task log or errors log, too. What did I do wrong?

More code:

#!/usr/bin/python3.6
import requests
import datetime
from pprint import pprint
import time
def goalsS():
    token = 'AQAAAAAFKNk4AAPquxxxxxxxxx'
    headers = {'Authorization': 'OAuth ' + token}
    countersDict = {18662179:'site.ru', 901167:'site.ru'}
    counterIds = [18662179, 901167]
    for cID in counterIds:
        names = []
        ng=[]
        url = "https://api-metrika.yandex.net/management/v1/counter/"+str(cID)+"/goals"
        r = requests.get(url, headers=headers)
        res = r.json()['goals']

        for i in res:
            ng.append(str(i['id'])+": "+ i['name']+'|')
            names.append(i['name'])

        goalsDict = dict(zip(ng,names))
        clear = str(ng).replace('[','').replace(']','').replace("'",'').replace(',','')
        with open(str(cID)+'goals_log.log','a') as log:
            print(clear, file =  log)
            log.close()
        li = []
        f = open(str(cID)+'goals_log.log', 'r')
        for line in f:
            line = set(line.rstrip("\n").split('|'))
            li.append(line)

        res2 = li[-1] - li[-2]
        if res2 == set():
            res2 = li[-2]-li[-1]
            print(res2,'set')
            if res2 == set():
                pass
            else:
                if cID == 18662179:
                    with open('toyota_goalss_log.txt','a') as log2:
                        print(str(datetime.date.today()) + ' ' + 'Удалили цель(и)'+' '+str(res2).replace(',','').replace('{','').replace('}',''),file = log2)
                    print(str(datetime.date.today()) + ' ' + 'Удалили цель\цели'+' '+str(res2),cID)
                    log2.close()
    else:
        if cID == 18662179:
                with open('toyota_goalss_log.txt','a') as log2:
                    print(str(datetime.date.today()) + ' ' + 'Создали цель(и)'+' '+str(res2).replace(',','').replace('{','').replace('}',''),file = log2)
                    print(str(datetime.date.today()) + ' ' + 'Создали цель\цели'+' '+str(res2),cID)
                    log2.close()

if __name__ == '__main__':
        goalsS()
1 Answers

Use absolute path to the file.

with open('/path/to/file','a') as log2:
    ...
Related