Python output file with timestamp

2019-08-01 01:47发布

Hi guys I have a little problem with output my file with time stamp here is my code

input_file  = open('DVBSNOOP/epg_slo_sort.txt', "r") # read
output_file = open('SORT/epg_slo_xml.txt', "w") # write 

for line in input_file:
    line = re.sub(r"\d{8}:|\d{7}:|\d{6}:|\d{5}:|\d{4}:","", line) # remove nubers from start line example --> 10072633: etc...
    line = line.replace("[=  --> refers to PMT program_number]","").replace("Service_ID:","Program") # remove =  --> refers to PMT program_number] and replace Service_ID to Program
    line = line.replace("0xdce","").replace("Start_time:","Start") # remove 0xdce and change Start_time to start
    line = line.replace("0x0","") # remove 0xdce 
    line = line.replace("event_name:","Title") # change to Title from event_name
    line = line.replace("Program: 14 (00e)","") # remove program 14 does not exist
    line = line.replace("-- Charset: ISO/IEC 8859  special table","") # remove -- Charset: ISO/IEC 8859  special table
    line = line.replace("-- Charset: ISO/IEC   special table","")# remove -- Charset: ISO/IEC   special table
    line = line.replace("[=","").replace("]","") # remove [=]
    line = line.replace("Duration:","Duration").replace("0x00","").replace("0x000","").replace("0x","")
    line = line.replace('"..',"").replace('"',"").replace(" . . .","").replace("-","") # remove ".."
    line = re.sub(r"Start: \d{2}|\d{4}|\d{3}|\d{7}\d{9}\d{6}","",line) # remove numbers after
    line = re.sub(r"Duration: \d{2}|\d{6}|\d{7}|d{5}\d{8}\d{4}|\d{3}|\d{9}","Duration",line) # remove numbers affter data
    line = re.sub(r"^//","",line) # remove / /
    line = re.sub(r"\([^)]*\)","",line) # remove brackets
    line = re.sub(r"Program 14","",line) # remove program 14
    output_file.write(line) # write to file

I want my output like epg_slo_sort(M;D;Y:Time).txt.

2条回答
Melony?
2楼-- · 2019-08-01 02:00

Is this what you're looking for? It returns a string in the format that you specify containing the time information you want:

 import time
 tme=time.localtime()
 timeString=time.strftime("%m,%d,%y,%H:%M:%S", tme)

Now all you need is to format it the way you want and append to the filename. There's multitude of ways to do it, a very crude but effective way would be:

 outFileName='epg_slo_xml'+timeString+'.txt'

Another way to do it would be to do something like this:

outFileName='epg_slo_xml{}.txt'.format(timeString)

but this will work in Python 2.7 and higher only. I don't use it (yet) but I'd suppose Python 3.X is similar.

查看更多
SAY GOODBYE
3楼-- · 2019-08-01 02:03

To generate a filename with a timestamp use strftime() from the time module to get the time in the necessary format and concatenate it with your file name pattern:

import time
current_time = time.strftime("%m.%d.%y %H:%M", time.localtime())
output_name = 'SORT/epg_slo_xml%s.txt' % current_time
output_file = open(output_name, "w")
查看更多
登录 后发表回答