1.問題一:定時任務問題
因為每天上午都要出一些關鍵性的報表,但是上午大家都來上班啦,在服務器上查數(shù)據(jù),匯成表都會和其他同事占資源,會導致運行較慢,所以打算在半夜運行代碼,下面介紹三種方式:
1.1 最簡單
import time
def doTh():
print("嘎嘎")
for i in range(5):
doTh()
time.sleep(10)
1.2 較復雜
import datetime
import time
def doTh():
print(嘎嘎')
# 假裝做這件事情需要一分鐘
time.sleep(60)
def go(h=0, m=0):
'''h表示設定的小時,m為設定的分鐘'''
while True:
# 判斷是否達到設定時間,例如0:00
while True:
now = datetime.datetime.now()
# 到達設定時間,結束內循環(huán)
if now.hour==h and now.minute==m:
break
# 不到時間就等20秒之后再次檢測
time.sleep(20)
# 做正事,一天做一次
doTh()
go()
1.3 復雜
相信這個網上也有很多介紹了,這里也就不多費口舌了

image.png
2.問題二:批量將txt文件轉化成csv文件
#識別當前目錄下的txt文件名
# -*- coding: utf-8 -*-
import os
import csv
def listdir(path, list_name,file_type): #傳入存儲的list
for file in os.listdir(path):
if os.path.splitext(file)[1] == file_type: #其中os.path.splitext()函數(shù)將路徑拆分為文件名+擴展名
file_path = os.path.join(path, file)
if os.path.isdir(file_path):
listdir(file_path, list_name)
else:
list_name.append(file_path)

image.png
接下來就是將這4個txt文件名獲取到

image.png
萬事具備,我們就可以開始轉成csv格式了
for files in list_name:
de = os.getcwd()+'/'
files = files.replace(de,"").replace("20190222ls.txt","")
new_file = files+".csv"
with open(new_file,'w',newline="") as csvfile:
spamwriter = csv.writer(csvfile, dialect='excel')
file = files+"20190222ls.txt"
with open(file, 'rb') as filein:
count = 0
for line in filein:
try:
flag = str(line,encoding="utf-8")
line_list = flag.strip('\\N\n').split('\001')
spamwriter.writerow(line_list)
count = count + 1
except:
count = count + 1
print("第{}行出現(xiàn)報錯,該行數(shù)值為{}".format(count,line_list))

可以看到已經有4個csv格式文件了,且去掉了20190222ls的后綴
。。。。。。。持續(xù)更新中