我有python程序,该程序从api读取数据并将其写入文件eth.txt。 我想编程每天创建一个带有日期名称的新文件,例如eth_9.11.2018.txt,eth_10.11.2018.txt,....,然后在上面写上。 你能帮我吗?
import time
import threading
import urllib
import datetime
while True:
ts = time.time()
h = datetime.datetime.fromtimestamp(ts).strftime('%H:%M:%S')
d = datetime.datetime.fromtimestamp(ts).strftime('%d.%m.%Y')
# read from API
ethash = urlopen('https://www.coincalculators.io/api/allcoins.aspx?hashrate=420000000&power=2000&powercost=0.15&difficultytime=0&algorithm=Ethash').read()
dataethash= json.loads(ethash)
global coinethash,algoethash,dayUSDethash,dayEUethash
coinethash = dataethash[0]["name"]
algoethash = dataethash[0]["algorithm"]
dayUSDethash = dataethash[0]["profitInDayUSD"]
diffethash = dataethash[0]["currentDifficulty"]
print ("Difficulty:"),diffethash
print ("Algoritm:"),algoethash
print ("Coin:"),coinethash
dayUSDethash = float(dayUSDethash)
dayEUethash = dayUSDethash*0.88
# Write ti file
profit = open("/home/pi/Skripte/eth.txt", "a")
profit.write(str(h))
profit.write('*')
profit.write(str(d))
profit.write('*')
profit.write(str(algoethash))
profit.write('*')
profit.write(str(diffethash))
profit.write('*')
profit.write(str(coinethash))
profit.write('*')
profit.write(str("%.2f" % dayEUethash))
profit.write('*')
profit.write("\n") #new line
print("OK")
time.sleep(500)
..顺便说一下... 是否可以以更友好和简短的方式阻止“ #write to file”写入? 它必须在单词之间包含一个字符*,并且必须用新行写出... 谢谢您的帮助!
答案 0 :(得分:0)
您可以动态定义要写入的文件的名称。
在这种情况下,eth_{}.txt'.format(d)
会在当天附加当天。
要更优雅地写入文件,您可以在字符串列表中以'*'一行。
with open('eth_{}.txt'.format(d), 'a') as profit:
profit.write('*'.join([str(x) for x in [h, d, algoethash, diffethash, coinethash, "%.2f" % dayEUethash, '\n']]))