脚本无法写入.txt文件。 Pythonanywhere

时间:2019-06-30 12:33:13

标签: python pythonanywhere

我有一个简单的脚本,用于yandex.metrika计数器目标记录。创建目标或将其删除到txt文件时写入。写入文本文件的代码:

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

如果我在pythonanywhere上的编辑器中单击“运行”按钮,则脚本将正确运行:没有错误,数据将附加到文本文件中。但是,如果我创建一个任务以每小时运行一次此脚本,则数据不会附加到文本文件中……并且任务日志或错误日志中也没有错误。我做错了什么?

更多代码:

#!/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 个答案:

答案 0 :(得分:0)

使用文件的绝对路径。

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