python動態修改檔案
# -*- coding:UTF-8 -*-
import time
import random
import io
import os
import datetime
print(u"請輸入重新整理時間間隔,單位秒:")
sec = input()
print(u"行情日期格式:YYYYMMDD,例如20190729")
print(u"請輸入日期:")
busidate=input()
print(u"檔案存放路徑,例如:F:/filename.txt")
print(u"請輸入檔案存放路徑:")
pathfile=input()
print(u"程式已開始執行")
while True:
f = io.open(str(pathfile), "r")#檔案存放位置,自行修改
data = f.readlines()
f.close()
f_new = io.open(str(pathfile), "w")#檔案存放位置,自行修改
i = 0
now_time = datetime.datetime.now().strftime('%Y%m%d-%H:%M:%S.%f')
for line in data:
if(i==0):
array_1= line.split('|')
old_time=array_1[6]
now_time = now_time[0:21]
temp = datetime.datetime.now().strftime('%Y%m%d')
now_time = now_time.replace(temp, str(busidate)) # 用系統日期替換電腦日期,保持檔案日期和系統日期一致,系統日期自行修改
line = line.replace(old_time, now_time)
i+=1
else:
array = line.split('|')
if(array[0] != "MD001" and array[0] != "TRAILER"):
if(array[0] == "MD004"):
array[34]=now_time[9:21]+'\n'
else:
array[32]=now_time[9:21]+'\n'
max_money = '%0.3f'%(float(array[5])*(1+0.1))
min_money = '%0.3f'%(float(array[5])*(1-0.1))
new_money = str(random.uniform(float(min_money) + 0.5, float(max_money) - 0.5))
buyflag = True #
for j in range(10,31):
if(j%2==0):
old_money = array[j - 1].strip()
if(j==10):
money = '%0.3f' % float(new_money)
else:
if(buyflag):
money = '%0.3f' % (float(new_money) - (float(j) - 10.000)/100)
buyflag = False
else:
money = '%0.3f' % (float(new_money) + (float(j) - 14.000)/100)
buyflag = True
array[j-1] = array[j-1].replace(old_money, money)
while(len(array[j-1]) < 11):
array[j-1] = ' ' + array[j-1]
while(len(array[j-1]) > 11):
array[j-1] = array[j-1].replace(" ","",1)
elif(array[0] == "MD001"):
array[12]=now_time[9:21]+'\n'
max_money_1 = '%0.4f' % (float(array[5]) * (1 + 0.1))
min_money_1= '%0.4f' % (float(array[5]) * (1 - 0.1))
new_money_1 = str(random.uniform(float(min_money_1) + 0.5, float(max_money_1) - 0.5))
old_money_1 = array[9].strip()
money_1 = '%0.4f' % float(new_money_1)
array[9] = array[9].replace(old_money_1, money_1)
while (len(array[9]) < 11):
array[9] = ' ' + array[9]
while (len(array[9]) > 11):
array[9] = array[9].replace(" ", "", 1)
line = '|'.join(array)
f_new.write(line)
f_new.close()
time.sleep(int(sec)) #間隔時間